Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

jQuery

Learn step by step



jQuery-Ajax

The jQuery continues its slogan "write less do more" in case of AJAX also. jQuery provides handy set of Functions to work with AJAX requests that otherwise needs lot of coding in case we are making java script ajax call.

What is AJAX in short?

In modern web sites we usually see web sites where data updates automatically without needing to refresh or reload the web page. Example: gmail automatically loads new emails. Facebook also loads stuff and news-feed automatically without reloading. This is done  by using AJAX that we can define as loading data in background without refreshing web site and displaying it on web page.

Another example of ajax can be sign up page or creating account page where we see there is no page refresh while account creates without page is reloaded.

AJAX stands for Asynchronous JavaScript and XML. As its name shows it uses java script to fulfill desired action. Normally we have to use lengthy java script code to accomplish that along with browser compatibility issues as different browsers requires different AJAX syntax for implementation.

The jQuery plays its role in that case and thanks to team of jquery that made this job quite easier for developers by allowing using jQuery methods and addressing compatibility issues along with simplifying AJAX based calls easier.

jQuery $.ajax() method

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

Syntax of ajax Function

$.ajax(name:value options)

Where

name:value options are set of pairs that specify AJAX request. All name or value parameters are optional that are described below.

url: URL to which request is sent in strong format

async: Default value is set to be true that means performing request asynchronously.

data: data to be send to server along with request

dataType: defining the data type expected from server as response

dataFilter: As server sends back data. This function is used to handle the raw data sent from server in advance. Complete syntax will be
dataFilter(data, type).

error: If request is failed this call back function is used. Complete syntax will be
error(xhr,status,error).

success: If AJAX request succeeds, A callback function to run. Its Complete syntax is: success(result,status,xhr)

global: A Boolean with a default value as True. It specifies whether global AJAX event handlers to be triggered or not.

jsonp: It overrides the callback function name in a jsonp request.

processData: A Boolean with default value of True. Tells whether to convert data into querystring or not sent in request.

timeout: Local timeout in milliseconds for the request.

type: Type of request (Get or post) default is Get.

username: This is user name for HTTP authentication access request

password: password for the HTTP authentication access request

$.ajax() method

Example given below loads a text file by using $.ajax method placed in same directory as source file that calls it. After the loading as button is clicked it will display loaded data from text file to ajaxrequest Div.


<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#loaddata").click(function(){
$.ajax({url:"ajaxexample.txt",success:function(ajaxresult){
$("#ajaxrequest").html(ajaxresult);
}});
});
});
</script>
</head>
<body>
<div>Click button to load AJAX returned data</div>
<div id="ajaxrequest"></div>
<button id="loaddata">Load data for ajaxrequest Div</button>
</body>
</html>
$.ajax() with PHP file to make AJAX Request

In example below, we will use text box entered data. Entered text in location and name boxes will be assigned to variables in jQuery. After button is clicked $.ajax() method will call URL= post_test.php file. It will receive sent parameters, location and name and return output string. All will be done without reloading the page.

Post_test.php file is placed at same location as our HTML file where $ajax() method is used.

If the AJAX call is successful the callback function will display returned data into "postrequest" Div.

First post_test.php code

<?php
$post_name=$_REQUEST["name"];
$post_location=$_REQUEST["location"];
if( $post_name )
{
echo "Name entered is: ". $post_name ."<br>";
echo "Location:" .$post_location;
}
?>
HTML file using $.ajax() method

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#loaddata").click(function(){
txtname=$("#txtinput").val();
txtlocation=$("#txtlocation").val();
$.ajax({url:"post_test.php",data:{name:txtname, location: txtlocation },success: function(ajaxresult){
$("#ajaxrequest").html(ajaxresult);
}});
});
});
</script>
</head>
<body>
<div id="ajaxrequest"></div>
Enter Name: <input type="text" id="txtinput"><br />
Enter Location: <input type="text" id="txtlocation"><br />
<button id="loaddata">Click to send request to post_test.php</button>
</body>
</html>

This is just basic example of using $.ajax() with php file sending text boxes data. In real time applications we may need to return database driven data also. If you learnt this correctly and understand how to use MySQL and PHP then you are almost ready to use database driven data for AJAX requests.

$.ajax with error handling

Below is similar example as above with error handling. Let's say if wrong file name is given it will show an alert:


<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#loaddata").click(function(){
txtname=$("#txtinput").val();
txtlocation=$("#txtlocation").val();
$.ajax({url:"post_test_11.php",data:{name:txtname, location: txtlocation },success: function(ajaxresult){
$("#ajaxrequest").html(ajaxresult);},error:function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);}
});
});
});
</script>
</head>
<body>
<div id="ajaxrequest"></div>
Enter Name: <input type="text" id="txtinput"><br />
Enter Location: <input type="text" id="txtlocation"><br />
<button id="loaddata">Click to send request to post_test.php</button>
</body>
</html>
Important methods for jQuery AJAX to learn

Generally $.ajax() function is not used directly. Because other available high level methods that are easier to use like $.post() and $.get() are used to perform ajax operations. These other methods use $.ajax() method underway.

Query $.post() method

jQuery $.ajaxSetup() method

jQuery $.load() method

jQuery $.post()method

jQuery $.get()method



Related Videos