The Ultimate Revelation Of jQuery AJAX method with 8 Examples & Codes

The Ultimate Revelation Of jQuery AJAX method with 8 Examples & Codes

This is the ultimate guide to jQuery AJAX—one of the most comprehensive resources you’ll find.

The best part?

You’ll learn 8 practical ways to implement jQuery AJAX in your website, complete with clear examples and easy-to-follow explanations.

Whether you’re just getting started or looking to improve your existing code, this guide will help you master jQuery AJAX with confidence. 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 most popular for doing AJAX tasks.

Using the .ajax() function, you can fetch data from Text, HTML, JSON, XML, API 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.

Syntax of jQuery AJAX Method

$.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:

NameValue
urlThe URL where AJAX request is made.
TypeThe HTTP method used – POST, GET, PUT, PATCH, DELETE.
DatatypeThe 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 pairs to be passed with the AJAX request.
Enter your name and click button

 

1. jQuery AJAX Method to Fetch Contents of a Text File

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.7.1/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:

url: "file.txt"
success: function (result,status,xhr) 
jQuery AJAX GET

Notice in the above code, I do not specify the Type parameter for the .ajax() function. So here it will 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"

2. jQuery AJAX Method to Fetch Contents of a HTML File

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.

3. Fetch JSON from jQuery AJAX

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, the URL of the JSON file is specified in the url field of the AJAX request. When the request is successful, the success callback function retrieves the JSON data and converts it into an HTML table. Finally, the generated HTML table is displayed inside a div element on the webpage..

fetch json with jquery ajax

4. Fetch XML file contents from jQuery AJAX

Just like I fetched JSON file’s content above, I can also fetch the contents of a 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:

fetch xml with jquery ajax

The product.xml file 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>

5. jQuery AJAX Error

You can use the error callback in jQuery AJAX to handle failed requests and display meaningful error messages to users. For example, try fetching a non-existent file using the jQuery AJAX method. When the request fails, the error function is triggered, allowing you to capture the error details and display the error message inside a div element. This approach helps you implement effective AJAX error handling and improve the user experience.

See the below code:

<button id="loadNoTextFile">Try</button>
<div id="textNoData"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></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.

Using .done() & .fail()

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)
});

6. jQuery AJAX to Call a PHP Page

The jQuery AJAX method allows you to call a PHP server-side script without reloading the page and send data to it asynchronously. By passing values through the AJAX request, you can process user input, interact with a database, and return a response from the PHP script, making your web application faster and more interactive.

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. Check the image:

jQuery ajax call php page

I have an input control for entering email address, a button to send this email to a PHP page.

<input id="email" placeholder="Subscribe to this blog with your email address." />
<button id="submit">Submit</button>
<div id="message"></div>

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>
  • Before calling the jQuery AJAX method I am validating the email. If the email is in correct syntax only then I call .ajax() method.
  • This .ajax() method in turn calls jquery-ajax-subscribe.php page. Through the data parameter I am passing the email value to it.

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.

7. jQuery AJAX method to Fetch Data from Database [ASP.NET Example]

The jQuery AJAX method enables you to perform a wide range of database operations without reloading the page, such as retrieving, inserting, updating, and deleting data. By sending asynchronous requests to a server-side application, you can create fast, responsive, and interactive web applications.

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.

Check it’s image:

jQuery AJAX Database Application

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.7.1/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>
  • In the above code dbData is the div where the products will be shown. The jQuery AJAX call is made on the loadDatabase click event.
  • I have passed the function’s name getproduct after the URL result.aspx. This C# function get’s called by the AJAX request.
  • Also note how I passed the dropdown values through the data object. Since the product data will be returned in string form so pass json for dataType key.
jQuery AJAX POST

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; }
}
  • The C# function getproduct must be a static and [WebMethod] so that the jQuery AJAX method is able to call it. Its parameters should be string and through them the dropdown values are supplied to it.
  • The getproduct function’s return type should be string. It filters the products using Linq and in the end creates an HTML (from the filtered products). This HTML is finally sent back as the AJAX response to the HTML page.
  • The LoadData() function creates some dummy products. You can replace this function to fetch real products from your Database.

The given image explains this whole process:

jquery ajax asp.net example

8. Call ASP.NET Core Minimal API with jQuery AJAX

The jQuery AJAX method makes it easy to call an ASP.NET Core Minimal API without refreshing the web page. By sending asynchronous HTTP requests, you can pass JSON data from the client to the Minimal API, process it on the server, and return a response in real time. This approach is ideal for building fast, interactive web applications that perform tasks such as fetching data, submitting forms, and updating database records while providing a smooth user experience.

This is my Minimal API code which inserts a new Work type on the database.

app.MapPost("/works", async (Work work, WorkDb db) =>
{
    db.Works.Add(work);
    await db.SaveChangesAsync();

    return Results.Created($"/works/{work.Id}", work);
});

The Work.cs class is:

public class Work
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string TimeStart { get; set; }

    public string TimeEnd { get; set; }

    public bool IsComplete { get; set; }
}

On the button click event I will insert a Work by calling the Minimal API with jQuery ajax code given below:

<button id="loadDatabase">Try</button>

<div id="dbData"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>
    var work = {
        id: 1,
        name: "Complete Documentation",
        timeStart: "09:00",
        timeEnd: "17:00",
        isComplete: false
    };

    $("#loadDatabase").click(function () {

        $.ajax({
            type: "POST",
            url: "/works",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(work),
            dataType: "json",

            success: function (result) {

                $("#dbData").html(
                    "<b>Id:</b> " + result.id + "<br>" +
                    "<b>Name:</b> " + result.name + "<br>" +
                    "<b>Start:</b> " + result.timeStart + "<br>" +
                    "<b>End:</b> " + result.timeEnd + "<br>" +
                    "<b>Completed:</b> " + result.isComplete
                );
            },

            error: function (xhr, status, error) {

                $("#dbData").html(
                    "Error: " + xhr.status + " " + xhr.statusText
                );
            }
        });

    });
</script>

JSON.stringify() is a JavaScript method that converts a JavaScript object into a JSON string before it is sent to the server. Here it converts the work class data supplied by the “work” variable.

On successful insertion, the Minimal API will return the created work back to the ajax method where it will be shown inside the div element.

Now It’s Your Turn

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:

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate