@manhng

Welcome to my blog!

Ajax (jQuery)

October 23, 2021 10:42

Ajax (edit)

Ajax - @manhng

Ajax (jQuery) - @manhng

Ajax - jQuery - EF Core - SqlCommand - @manhng

jQuery.ajax() | jQuery API Documentation

When to use async false and async true in ajax function in jquery - Stack Overflow

Đồng bộ (async: false) - Tập lệnh dừng và chờ máy chủ gửi lại câu trả lời trước khi tiếp tục. Có một số tình huống trong đó Ajax đồng bộ là bắt buộc.

Không đồng bộ (async: true) - Trường hợp tập lệnh cho phép trang tiếp tục được xử lý và sẽ xử lý trả lời nếu và khi nó đến. Nếu có bất cứ điều gì sai trong yêu cầu và/hoặc chuyển tệp, chương trình của bạn vẫn có khả năng nhận ra sự cố và khắc phục sự cố đó.

You set async to false, when you need that ajax request to be completed before the browser passes to other codes:

<script>

// ... $.ajax(... async: false ...); // Hey browser! first complete this request, then go for other codes $.ajax(...); // Executed after the completion of the previous async:false request
// ...
</script>

Đặt async thành false có nghĩa là câu lệnh bạn đang gọi phải hoàn thành trước khi câu lệnh tiếp theo trong hàm của bạn có thể được gọi. Nếu bạn đặt async: true thì câu lệnh đó sẽ bắt đầu thực thi và câu lệnh tiếp theo sẽ được gọi bất kể câu lệnh async đã hoàn thành chưa.

<script>
var url = "http://service.example.com";
$
(document).ready(function(){
  $
("button").click(function(){
    $
.ajax({
      type
:"GET",
      url
:url,
      async
:true,
      dataType
: "json",
      success
: function(json) {
       
// Parse the response.
     
// Do other things.
     
},
      error
: function(xhr, status, err) {
     
// This is where we end up!
     
}
   
});
 
});
});
</script>

ASP.NET MVC: Using JavaScript with Ajax and Razor view

October 8, 2019 19:41

ASP.NET MVC: Using JavaScript with Ajax and Razor view

https://bitoftech.net/

View

<button id="btnGetData" type="button" class="btn btn-primary"> @Resources.GetData</button>

Controller

The complete list of objects is (they all receive the ControllerContext as the contructor parameter):

  • FormValueProvider: search for data in the body (Request.Form)
  • RouteDataValueProvider: search for data in the route (RouteData.Value)
  • QueryStringValueProvider: search for data in the query string (Request.QueryString)
  • HttpFileCollectionValueProvider: search for uploaded files (Request.Files)

System.Web.Mvc.HttpPostAttribute & System.Web.Http.HttpPostAttribute

  • System.Web.Mvc.HttpPostAttribute
  • System.Web.Http.HttpPostAttribute

IHttpActionResult & HttpResponseMessage

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

https://www.infoworld.com/article/3192176/my-two-cents-on-using-the-ihttpactionresult-interface-in-webapi.html

ihttpactionresult

[FromBody]

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api#using-frombody

FromBodyAttribute Class (System.Web.Http)

// POST /api/Product/Post
[HttpPost]
public HttpResponseMessage Post([FromBody] Product product)
{
var name = product.Name; // "Product Name"
var price = product.Price; // 0.50
}

Model Binding

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

You can use one of the following attributes to specify the source to use for any given target:

Model

// a complex object
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}

JSON

{
  "Name" : "Product Name",
  "Price" : 0.50 
}

Action Get

// GET: /Home/GetData
[HttpGet]
public ActionResult GetData()
{
    try
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
        string redirectUrl = Utilities.GetPageUrl(actionName, controllerName);
        string loginUrl = Utilities.GetLoginUrl();
        string loginUrlEncrypted = loginUrl;
        ViewBag.Url = loginUrl + redirectUrl;
        return Json(new { Success = true, Data = loginUrlEncrypted }, JsonRequestBehavior.AllowGet);
    }
    catch
    {
        return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
    }
}

Action Post

// POST: /Home/SaveData
[HttpPost]
public ActionResult SaveData([FromBody] Product product)
{
    try
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
        bool success = Utilities.SaveProduct(product);
        return Json(new { Success = success, Message = "Success" }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { Success = false, Message = ex.ToString() }, JsonRequestBehavior.AllowGet);
    }
}

Call AJAX using JavaScript / jQuery

<script>
window.HomeSaveData = '@Url.Action("SaveData", "Home")';
$(function () {
var obj =
{
"Name" : "Product Name",
"Price" : 0.50
};
debugger;
$.ajax({
url: window.HomeSaveData,
type: "POST",
dataType: "json",
data: JSON.stringify(obj);
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
debugger;
if (resultData.Success = false) {
debugger;
} else {
var message = resultData.Message;
debugger;
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
timeout: 120000
});
});
</script>

Call AJAX using JavaScript / jQuery

<script>
window.HomeGetData = '@Url.Action("GetData", "Home")';
$(function () {
$.ajax({
url: window.HomeGetData,
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
debugger;
if (resultData.Success = false) {
debugger;
} else {
var data = resultData.Data;
debugger;
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
timeout: 120000
});
});
</script>

ASP.NET MVC 5 and jQuery

May 6, 2019 21:23

ASP.NET MVC 5 Source Samples (edit)

Training Course

https://www.interfacett.com/training/dev500-building-an-html5-end-to-end-web-application-with-asp-net-mvc5-ef-code-first-and-jquery/

https://www.wintellect.com/course/building-html5-apps-with-asp-net-mvc-ef-code-first-and-jquery/

http://takenote.com/training/modern-web-development-using-microsoft-asp-net-mvc-5/

https://www.u2u.be/training/asp.net-programming

Building ASP.NET MVC Apps with EF Code First, HTML5, and jQuery

https://www.pluralsight.com/courses/web-development

Tutorials

https://www.sitepoint.com/10-javascript-jquery-mvc-tutorials/

https://www.codemag.com/Article/1405071/10-Good-Practices-for-ASP.NET-MVC-Apps

https://www.tutorialsteacher.com/mvc/asp.net-mvc-tutorials

Dashboard Application With ASP.NET MVC 5 And jQuery

https://www.c-sharpcorner.com/article/dashboard-application-with-asp-net-mvc-5-and-jquery/

GitHub Source

https://github.com/manhnguyenv/Dashboard-Appplication

Decode & Encode with Base 64 in JavaScript

https://scotch.io/tutorials/how-to-encode-and-decode-strings-with-base64-in-javascript

https://www.jqueryscript.net/text/Base64-Decode-Encode-Plugin-base64-js.html

https://www.url-encode-decode.com/base64-encode-decode/

JSON Data with Asp.Net MVC using JQuery

http://www.mukeshkumar.net/articles/mvc/json-data-with-asp-net-mvc-using-jquery

Upload Image

https://www.codeproject.com/Articles/1095619/Generic-Repository-Pattern-in-ASP-NET-MVC

Account At a Glance Application

https://weblogs.asp.net/dwahlin/building-the-account-at-a-glance-html5-jquery-application (HAY HAY HAY)

image

https://github.com/DanWahlin/AccountAtAGlance

This application provides an end-to-end look at how multiple technologies can be integrated including:

  • ASP.NET MVC
  • Web API
  • Entity Framework and Model Objects
  • The Data Repository Pattern
  • Dependency Injection using the Unity IoC container
  • LINQ to XML (to parse remote XML financial feeds)
  • jQuery
  • jQuery UI Drag and Drop
  • Handlerbars HTML templates
  • Modernizr
  • HTML5 (Canvas and SVG for charting)
  • More...

ASP.NET MVC 5, EF6, DDD, IoC

https://github.com/manhnguyenv/Asp.net_MVC5_DDD_EF6_IoC

ASP.NET MVC 5 and Xamarin

https://github.com/manhnguyenv/empleo-dot-net

Unit of Work + Repository Pattern in MVC5 and Web API 2 with Fluent Nhibernate

https://github.com/manhnguyenv/mvc5-unit-of-work-example

ASP.NET MVC with jQuery AJAX (HAY)

https://www.codaffection.com/asp-net-mvc-tutorial/asp-net-mvc-with-jquery-ajax/

https://www.tutlane.com/tutorial/aspnet-mvc/use-of-javascript-jquery-ajax-css-and-bootstrap-in-asp-net-mvc

https://medium.com/@yogihosting/tutorial-implementing-jquery-ajax-with-entity-framework-in-asp-net-mvc-eda1e3048a25

https://www.c-sharpcorner.com/UploadFile/302f8f/Asp-Net-mvc-using-jquery-ajax/

ASP.NET MVC 5 with JavaScript and jQuery

https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views

ASP.NET MVC 5 with Chart

https://canvasjs.com/docs/charts/integration/asp-net-mvc-charts/

Automatically Optimize CSS, JavaScript

https://zoompf.com/blog/2015/01/automatically-optimize-css-javascript-asp-net/

Validation

http://www.vbforums.com/showthread.php?822093-ASP-NET-MVC-5-Form-Validation-using-jQuery-and-Bootstrap-without-Model-class

https://exceptionnotfound.net/asp-net-mvc-demystified-unobtrusive-validation/

Localization

https://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx

Calendar

https://gunnarpeipman.com/aspnet/using-fullcalendar-jquery-component-with-asp-net-mvc/

Password Meter jQuery

https://www.asmak9.com/2016/09/aspnet-mvc5-password-meter-jquery.html

jQuery, AJAX and ASP.NET MVC 5

https://www.c-sharpcorner.com/UploadFile/302f8f/Asp-Net-mvc-using-jquery-ajax/

jTable and ASP.NET MVC 5

http://www.howtobuildsoftware.com/index.php/how-do/bEfn/jquery-aspnet-mvc-aspnet-mvc-5-jquery-jtable-integrating-jtable-jquery-into-an-aspnet-mvc-5-project-that-uses-a-default-layout

https://www.codeproject.com/Articles/277576/AJAX-based-CRUD-tables-using-ASP-NET-MVC-and-jTa

jTable overview

CRUD in HTML, JavaScript, and jQuery Using the Web API

https://www.codemag.com/Article/1601031/CRUD-in-HTML-JavaScript-and-jQuery-Using-the-Web-API

INTEGRATE MULTISELECT PLUGIN WITH ASP.NET MVC 5 AND JQUERY

https://tajuddin.chittagong-it.com/integrate-multiselect-plugin-with-asp-net-mvc-5-and-jquery/

ASP.NET MVC 5 and Real Time App Using Signalr

https://www.c-sharpcorner.com/article/transform-an-existing-mvc-app-to-a-real-time-app-using-signalr/

https://www.codeguru.com/csharp/.net/sending-notifications-using-asp.net-signalr.htm

  1. Knowledge of ASP.NET MVC5.
  2. Knowledge of jQuery
  3. Knowledge of HTML.
  4. Knowledge of JavaScript.
  5. Knowledge of AJAX.
  6. Knowledge of CSS.
  7. Knowledge of Bootstrap.
  8. Knowledge of C# Programming.
  9. Knowledge of C# LINQ.
  10. Knowledge of SQL Server

jQuery Plugin Full Calendar

https://www.c-sharpcorner.com/article/asp-net-mvc5-full-calendar-jquery-plugin/

Select2 in ASP.NET MVC 5 (HAY)

https://www.intertech.com/Blog/selecting-multiple-items-using-select2-in-mvc-5/

http://www.datahaunting.com/mvc/select2-simple-example-in-asp-net-mvc/

https://stackoverflow.com/questions/23417594/data-binding-in-mvc-5-and-select2-multiple-values-with-razor-engine

https://blog.e-zest.com/tech-tutorial-select2-with-asp.net-mvc

JavaScript MVC

https://github.com/manhnguyenv/Javascript-MVC-App

https://github.com/manhnguyenv/minimal-todo-js-mvc

https://github.com/manhnguyenv/MVC-Vanilla-Javascript

ASP.NET MVC3 Razor With jQuery For Beginners

https://www.codeproject.com/Articles/344292/ASP-NET-MVC-Razor-With-jQuery-For-Beginners

Enhancing HTML tables using the jQuery DataTables plug-in

https://www.codeproject.com/Articles/194916/Enhancing-HTML-tables-using-a-JQuery-DataTables-pl

jQuery DataTables and ASP.NET MVC Integration - Part I

https://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part

A jQuery UI-Based Date Picker for ASP.NET MVC 5

https://www.codeguru.com/csharp/.net/net_asp/a-jquery-ui-based-date-picker-for-asp.net-mvc-5.html

 

Cách sử dụng jQuery

August 24, 2018 10:13

Cách sử dụng jQuery (edit)

http://jsbin.com/moyohevuna/edit?js,console

Cập nhật thông tin lương của các ngành năm 2018

https://www.fa.net.vn/media/first-alliances/client/Salary%20Guide/vietnam-salary-2018-first-alliances.pdf

Cách tính lương hưu

https://baohiemxahoidientu.vn/bhxh/cach-tinh-luong-huu-va-tro-cap-mot-lan-khi-nghi-huu.html

Series jquery

July 30, 2018 13:15

Series jquery (edit)

Working with HTML Table

Ví dụ bạn muốn thao tác trên cột 2 với điều kiện lọc dữ liệu lấy từ cột 10 như hình dưới:

var table = $('form > table')[0];
var tr = $(table).find('tbody > tr');
$(tr).find('td:nth-child(10)').each(function () {
  var parent = $(this).parent();
  var isBold = $.trim($(this).text()) === "True";
  if (parent.length > 0 && isBold) {
    var bold = $(parent).find('td:nth-child(2)');
    //console.log($(bold).text());
    $(bold).css("font-weight","bold");​
  }
});

Thực hành jQuery

November 9, 2017 13:04

Thực hành HTML+CSS+JavaScript

Dynamically Change Form Action Using Javascript

HTML

<!DOCTYPE html>
<html>
<head>
<title>Dynamically Change Form Action Using Javascript</title>
<!-- Include jQuery Library and File Here -->
<script type="text/javascript" src="js/form_action.js"></script>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="container">
<div class="main">
<h2>Dynamically Change Form Action Using Javascript</h2>
<form id="form_id" method="post" name="myform">
<label>Name :</label>
<input type="text" name="name" id="name"/>
<label>Email :</label>
<input type="text" name="email" id="email"/>
<label>Set Form Action :</label>
<select id="form_action" onChange="select_change()" >
<option value="">--- Set Form Action ---</option>
<option value="first.php">first.php</option>
<option value="second.php">second.php</option>
<option value="third.php">third.php</option>
</select>
<input type="button" value="Submit" onclick="myfunction()"/>
</form>
</div>
</div>
</body>
</html>

CSS

/* Below line is used for online Google font */
@import url(http://fonts.googleapis.com/css?family=Raleway);
h2{
background-color: #FEFFED;
padding: 30px 35px;
margin: -10px -50px;
text-align:center;
border-radius: 10px 10px 0 0;
}
.back{
font-size: 14px;
padding: 5px 15px;
text-decoration: none;
color: white;
background-color: rgb(34, 128, 172);
border-radius: 3px;
border: 1px solid rgb(9, 78, 133);
}
hr{
margin: 10px -50px;
border: 0;
border-top: 1px solid #ccc;
margin-bottom: 40px;
}
div.container{
width: 900px;
height: 610px;
margin:35px auto;
font-family: 'Raleway', sans-serif;
}
div.main{
width: 300px;
padding: 10px 50px 25px;
border: 2px solid gray;
border-radius: 10px;
font-family: raleway;
float:left;
margin-top:30px;
}
input[type=text],select{
width: 95%;
height: 25px;
padding: 5px;
margin-bottom: 25px;
margin-top: 5px;
border: 2px solid #ccc;
color: #4f4f4f;
font-size: 16px;
border-radius: 5px;
}
select{
width: 100%;
height:40px;
font-family:cursive;
font-size: 20px;
}
label{
color: #464646;
text-shadow: 0 1px 0 #fff;
font-size: 14px;
font-weight: bold;
}
input[type=button]{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 100%;
border-radius: 5px;
margin-bottom:10px;
padding: 10px 0;
}
input[type=button]:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}

JavaScript

function select_change() {
var z = document.getElementById("form_action").selectedIndex;
var z1 = document.getElementsByTagName("option")[z].value;
alert("Form action changed to " + z1);
}
function myfunction() {
if (validation()) {
// Calling Validation function.
//select option value from select tag and storing it in a variable.
var x = document.getElementById("form_action").selectedIndex;
var action = document.getElementsByTagName("option")[x].value;
if (action !== "") {
document.getElementById("form_id").action = action;
document.getElementById("form_id").submit();
} else {
alert("Please set form action");
}
}
}
// Name and Email validation Function.
function validation() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if (name === '' || email === '') {
alert("Please fill all fields...!!!!!!");
return false;
} else if (!(email).match(emailReg)) {
alert("Invalid Email...!!!!!!");
return false;
} else {
return true;
}
}

Thực hành jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input type='radio' value='/dkm-cln' name='linkgroup' id="linkgroup_1" />
<label for='linkgroup_1'>Chọn thằng cln</label>
<input type='radio' value='/dkm-mmm' name='linkgroup' id="linkgroup_2"/>
<label for='linkgroup_1'>Chọn thằng mmm</label>
<hr /><span></span>
<script>
$(() => {
    $('input[name=linkgroup]').on('change', (event) => {
        $('span').text($(event.target).val());
    })
})
</script>
</body>
</html>

Categories

Recent posts