JS | AJAX

AJAX: Asynchronous Javascript and XML.

To create a AJAX 「XMLHTTP Request Object」

Traditionally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

function loadDoc() {

var xhttp;

if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};

xhttp.open("GET", "ajax_info.txt", true);

xhttp.send();
}

Jquery

The purpose of jQuery is to make it much easier to use JavaScript on your website.

1
2
3
4
5
6

$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
1
2
3
4
5
6
7
8
9
10
11

$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
});

GET or POST?

Two commonly used methods for a request-response between a client and server are: GET and POST.

  1. GET - Requests data from a specified resource
  2. POST - Submits data to be processed to a specified resource
  3. GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

  1. A cached file is not an option (update a file or database on the server).
  2. Sending a large amount of data to the server (POST has no size limitations).
  3. Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Jquery get
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});

// Jquery post
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});

AJAX Methods

.ajax()

$.ajax({name:value, name:value, ... })

The ajax() method is used to perform an AJAX (asynchronous HTTP) request.

All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

Main Parameters:

Name Value / Description
async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true.
data Specifies data to be sent to the server.
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
success(result,status,xhr) A function to be run when the request succeeds.
timeout The local timeout (in milliseconds) for the request.
type Specifies the type of request. (GET or POST).
url Specifies the URL to send the request to. Default is the current page.
xhr A function used for creating the XMLHttpRequest object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});

$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "wrongfile.txt", error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
});

.get()

$.get(URL,data,function(data,status,xhr),dataType)

The $.get() method loads data from the server using a HTTP GET request.

Main Parameters:

Name Value / Description
URL Required. Specifies the URL you wish to request.
data Optional. Specifies data to send to the server along with the request.
function(data,status,xhr) Optional. Specifies a function to run if the request succeeds. Additional parameters: 1) data - contains the resulting data from the request; 2) status - contains the status of the request (“success”, “notmodified”, “error”, “timeout”, or “parsererror”); 3) xhr - contains the XMLHttpRequest object.
dataType Optional. Specifies the data type expected of the server response.

By default jQuery performs an automatic guess.
Possible types: xml, html, json, txt…

.getJson()

$(selector).getJSON(url,data,success(data,status,xhr))

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

Main Parameter
Name | Description
— | —
url | Required. Specifies the url to send the request to.
data | Optional. Specifies data to be sent to the server.
success(data,status,xhr) |Optional. Specifies the function to run if the request succeeds: 1) data - contains the data returned from the server;
2) status - contains a string containing request status (“success”, “notmodified”, “error”, “timeout”, or “parsererror”);
3) xhr - contains the XMLHttpRequest object.

1
2
3
4
5
6
7
8

$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});

.load()

$(selector).load(url,data,function(response,status,xhr))

The load() method loads data from a server and puts the returned data into the selected element.

Note: There is also a jQuery Event method called load. Which one is called, depends on the parameters.

.post()

$(selector).post(URL,data,function(data,status,xhr),dataType)

The $.post() method loads data from the server using a HTTP POST request.

Main Parameter:

Name Description
URL Required. Specifies the url to send the request to.
data Optional. Specifies data to send to the server along with the request.

function(data,status,xhr) Optional. Specifies a function to run if the request succeeds.
dataType | Optional. Specifies the data type expected of the server response.
By default jQuery performs an automatic guess.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});

$(document).ready(function(){
$("input").keyup(function(){
var txt = $("input").val();
$.post("demo_ajax_gethint.asp", {suggest: txt}, function(result){
$("span").html(result);
});
});
});

.param()

$.param(object,trad)

The param() method creates a serialized representation of an array or an object.

The serialized values can be used in the URL query string when making an AJAX request.

Main Parameters:

Parameter | Description
object | Required. Specifies an array or object to serialize
trad | Optional. A Boolean value specifying whether or not to use the traditional style of param serialization

1
2
3
4
5
6
7
8
9
10
11
12
13

$(document).ready(function(){
personObj = new Object();
personObj.firstname = "John";
personObj.lastname = "Doe";
personObj.age = 50;
personObj.eyecolor = "blue";
$("button").click(function(){
$("div").text($.param(personObj));
});
});

// Output: firstname=John&lastname=Doe&age=50&eyecolor=blue

.serialize()

$(selector).serialize()

The serialize() method creates a URL encoded text string by serializing form values.

You can select one or more form elements (like input and/or text area), or the form element itself.

The serialized values can be used in the URL query string when making an AJAX request.

1
2
3
4
5
6
7
8

$(document).ready(function(){
$("button").click(function(){
$("div").text($("form").serialize());
});
});

// Output: FirstName=Mickey&LastName=Mouse

.serializeArray()

$(selector).serializeArray()

The serializeArray() method creates an array of objects (name and value) by serializing form values.

You can select one or more form elements (like input and/or text area), or the form element itself.

1
2
3
4
5
6
7
8
9
10
11

$(document).ready(function(){
$("button").click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " ");
});
});
});

// Output: FirstName:Mickey LastName:Mouse

.ajaxStart()

$(document).ajaxStart(function())

The ajaxStart() method specifies a function to be run when an AJAX request starts.

Note: As of jQuery version 1.8, this method should only be attached to document.

1
2
3
4
5
6
7
8
9

$(document).ready(function(){
$(document).ajaxStart(function(){
$(this).html("<img src='demo_wait.gif'>");
});
$("button").click(function(){
$("div").load("demo_ajax_load.asp");
});
});

.ajaxStop()

$(document).ajaxStop(function())

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed.

When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

Note: As of jQuery version 1.8, this method should only be attached to documents.

1
2
3
4
5
6
7
8
9
$(document).ready(function(){
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
$("button").click(function(){
$("div").load("demo_ajax_load.txt");
$("div").load("demo_ajax_load.asp");
});
});

References:

  1. All Examples from W3schools:

  2. http://blog.csdn.net/mm_bit/article/details/49096595