This is the most comprehensive guide to jQuery AJAX on the planet.
The best part?
I’m going to show you 7 ways to implement jQuery AJAX in your website.
In short: if you want to implement jQuery AJAX, you’ll love this guide.
Let’s get started.
AJAX stands for Asynchronous JavaScript and XML. A Web Developer uses jQuery AJAX to update parts of a web page without reloading the whole page (also known as Asynchronous Update). The .ajax() method of jQuery is the most used for doing AJAX tasks.
Using the .ajax() function you can fetch data from Text, HTML, JSON, XML or any external file with no page reloading. Once this data is fetches, it can be easily shown in a div, textbox or any other HTML control.
$.ajax({name:value, name:value, .. })
Note: The name:value in the syntax are the sets of key-value pairs that are used to configure the AJAX request. They are optional.
The important name-value pairs are:
Name | Value |
---|---|
url | The URL to where AJAX request is made. |
Type | The HTTP method used – POST or GET. |
Datatype | The type of data returned from the AJAX request. Can be xml, json, script, or html. |
success(result,status,xhr) | The function to call when the AJAX request is successful. All 3 parameters are optional. The result parameter will get the return value from the AJAX request. |
error(xhr,status,error) | The function to call when AJAX request fails. All 3 parameters are optional. Helps in debugging during error. |
data: ‘{“k1″:”v1″,”k2″:”v2”,..}’ | The key-value to be passed with the AJAX request. |
Let’s fetch a text file content with jQuery AJAX. See the below code:
<button id="loadTextFile">Try</button>
<div id="textData"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#loadTextFile").click(function (e) {
$.ajax({
url: "file.txt",
success: function (result,status,xhr) {
$("#textData").html(result);
}
});
});
});
</script>
The jQuery AJAX is called on the button click event. The textData div will show the text file’s content. Note how I have passed the url and function in the name:value manner.
Notice in the above code, I do not specify the Type parameter for the .ajax() function. So here it will mean to perform the HTTP GET type of AJAX call (HTTP GET is the default value).
If you want to make the HTTP POST type of AJAX call then specify the type value as ‘Post’:
type: "POST"
In the below code I am fetching contents of the HTML file just like what I did for the text file earlier.
<button id="loadHtmlFile">Try</button>
<div id="htmlData"></div>
$("#loadHtmlFile").click(function (e) {
$.ajax({
url: "file.html",
success: function (result, status, xhr) {
$("#htmlData").html(result);
}
});
});
Here, on the button click event, I am fetching contents of a file called ‘file.html’ with jQuery AJAX and then showing it in a div element.
A JSON file can also be fetched with jQuery AJAX just like a Text file. Let us see this with an example. The JSON file syntax is given below:
[
{
"Product": "Mini Skirt size 38",
"color": "Brown",
"Price": "$40.77"
},
{
"Product": "Women Pant size 39",
"color": "Black",
"Price": "$21.45"
},
{
"Product": "Men Coat size 47",
"color": "Pink",
"Price": "$101.50"
}
]
To fetch this JSON file write the below code:
$.ajax({
url: "product.json",
success: function (result, status, xhr) {
var table = $("<table><tr><th>Product</th><th>Color</th><th>Price</th></tr>");
var tr;
for (var i = 0; i < result.length; i++) {
tr = $("<tr>");
tr.append("<td>" + result[i].Product + "</td>");
tr.append("<td>" + result[i].color + "</td>");
tr.append("<td>" + result[i].Price + "</td>");
tr.append("</tr>");
table.append(tr);
}
table.append("</table>");
$("#jsonData").html(table);
}
});
In the above code, JSON file location is given on for the url field, then in the success function, the fetched JSON is parsed in the HTML table format. Finally this HTML is shown in a div.
Just like I fetched JSON file’s content above, I can also fetch the contents of an XML file with my jQuery AJAX code. Check the below code with does this work:
<button id="loadXmlFile">Try</button>
<div id="xmlData"></div>
$("#loadXmlFile").click(function (e) {
$.ajax({
url: "product.xml",
success: function (result, status, xhr) {
var table = "<table><tr><th>Name</th><th>Color</th><th>Price</th></tr>";
var cols="";
$("product", result).each(function (i) {
tdCol = "<td>" + $(this).find("name").text() + "</td>";
tdCol += "<td>" + $(this).find("color").text() + "</td>";
tdCol += "<td>" + $(this).find("price").text() + "</td>";
cols += "<tr>" + tdCol + "</tr>";
});
table += cols + "</table>";
$("#xmlData").html(table);
}
});
});
On the button click the XML file content is read and looped through using the .each() method. These contexts are then shown in an HTML table, as shown by the below image:
The product.xml file context is:
<?xml version="1.0" encoding="utf-8" ?>
<products>
<product>
<name>Mini Skirt size 38</name>
<color>Brown</color>
<price>$40.77</price>
</product>
<product>
<name>Women Pant size 39</name>
<color>Black</color>
<price>$21.45</price>
</product>
<product>
<name>Men Coat size 47</name>
<color>Pink</color>
<price>$101.50</price>
</product>
</products>
You can use the error parameter to call a function in case of receiving any jQuery AJAX Error. To understand it, let us fetch a non-existing file using jQuery AJAX method and show the error message inside a div.
See the below code:
<button id="loadNoTextFile">Try</button>
<div id="textNoData"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#loadNoTextFile").click(function (e) {
$.ajax({
url: "no-file.txt",
success: function (result, status, xhr) {
$("#textNoData").html(result)
},
error: function (xhr, status, error) {
$("#textNoData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
});
</script>
Here the error function is called and you will get Result: error Not Found 404 Not Found on clicking the button.
You can also use .done() & .fail() deferred objects in place of success & error callback functions. See below code:
$.ajax({
url: "file.txt"
}).done(function (result, status, xhr) {
alert(result)
}).fail(function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
});
You can call a server side page in PHP by using the jQuery AJAX method and pass values to it.
For example here I will send an email address from text box to a PHP page. This PHP page will insert this email in the database and sends the success or failure message back.
<input id="email" placeholder="Subscribe to this blog with your email address." />
<button id="submit">Submit</button>
<div id="message"></div>
I have an input control for entering email address, a button to send this email to a PHP page.
My jQuery Code is:
<script>
$(document).ready(function () {
$("#submit").click(function (e) {
var result = Validate();
if (result == true) {
$.ajax({
type: "POST",
url: "jquery-ajax-subscribe.php",
data: {email: $("#email").val()},
success: function (msg) {
$("#message").html(msg);
},
error: function (req, status, error) {
alert(req + " " + status + " " + error);
}
});
}
return false;
});
function EmailValidate() {
var numericExpression = /^\w.+@[a-zA-Z_-]+?\.[a-zA-Z]{2,3}$/;
var elem = $("#email").val();
if (elem.match(numericExpression))
return true;
else
return false;
}
function Validate() {
var errorMessage = "";
//Email
if ($("#email").val() == '')
errorMessage += " Enter your email address<br/>";
else if (!(EmailValidate()))
errorMessage += " Invalid email address<br/>";
//End
$("#message").html(errorMessage);
if (errorMessage.length == 0)
return true;
else
return false;
}
});
</script>
The jquery-ajax-subscribe.php code is:
<?php $email = $_REQUEST['email'];
//Make database operations and insert the email value in the database. If insert operation is successful echo "You are subscribed." else "Something went wrong. Try again.".
//I am assuming that the operation is successful and so returning the "You are subscribed." message back to jQuery AJAX method.
echo "'" . $email ."' subscribed successfully.";
?>
The PHP page fetches the email value using $_REQUEST['email']
, inserts it to the database and then returns the message using the echo method.
The jQuery AJAX method allows you can do any type of Database operations, like fetching data from DB or inserting data to DB.
Let’s create an ecommerce demo application that allows users to fetch data from DB. In this application I will make a jQuery AJAX call from an HTML page to the .ASPX (asp.net) page. The HTML page has 2 dropdowns that contains the product category names and product price range.
User has to select the values in both of the dropdowns. On clicking the button the dropdown selected values are passed with the AJAX call to the .ASPX page.
The .ASPX page queries the database and filters the products based on the dropdown values. Finally it returns all the filtered products as the AJAX response. The HTML page then shows the products inside a div.
The HTML page code:
<select id="productCategory">
<option value="Select">Select Product Category</option>
<option value="Skirts">Skirts</option>
<option value="Pants">Pants</option>
<option value="Electronics">Electronics</option>
</select>
<select id="productPrice">
<option value="Select">Select Product Price</option>
<option value="<100">Less than $100</option>
<option value=">=100">More than $100</option>
</select>
<button id="loadDatabase">Try</button>
<div id="dbData"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$("#loadDatabase").click(function (e) {
$.ajax({
type: "POST",
url: "result.aspx/getproduct",
contentType: "application/json; charset=utf-8",
data: '{"productCategory":"' + $("#productCategory").val() + '","productPrice":"' + $("#productPrice").val() + '"}',
dataType: "json",
success: function (result, status, xhr) {
$("#dbData").html(result.d);
},
error: function (xhr, status, error) {
$("#dbData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
</script>
Here I specified the type: “POST” in the .ajax() function. So here HTTP POST type of AJAX call will be performed.
The .ASPX page code:
static List<Product> product;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getproduct(string productCategory, string productPrice)
{
product = new List<Product>();
LoadData();
var result = (List<Product>)null;
if (productPrice == "<100")
result = product.Where(x => x.categoryName == productCategory & x.price < 100).ToList();
else
result = product.Where(x => x.categoryName == productCategory & x.price >= 100).ToList();
StringBuilder sb = new StringBuilder();
foreach(Product p in result)
sb.Append("<div class=\"product\"><img src=\""+p.image+ "\" /><span>"+p.name+"</span><span>$ "+p.price+"</span></div>");
return sb.ToString();
}
static void LoadData()
{
product = new List<Product>();
product.Add(new Product() { name = "Vanheusen Women's Skirt", image = "Image/s1.jpg", categoryName = "Skirts", price = 20.89M });
//Add more products
}
class Product
{
public string name { get; set; }
public string image { get; set; }
public string categoryName { get; set; }
public decimal price { get; set; }
}
Download source codes:
Now you have learned everything about .ajax() method from this Tutorial.
Or maybe you have a question.
I am ready to answer.
Either way, leave a comment below right now. Also check out these other related topics in AJAX: