jQuery AJAX Complete Guide for Beginners and Experts

jQuery AJAX Complete Guide for Beginners and Experts

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 “Partial Page Refresh”). The ajax() method is used to perform AJAX operations in jQuery.

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, you can easily show it 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” that are used to configure the AJAX request. All of them 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.
Enter your name and click button

jQuery AJAX Method to Fetch Contents of a Text File

Let’s fetch text file’s 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.

DEMO

The above code can also be use to fetch contents of other file types like HTML, JSON, XML, etc.

Fetch JSON from jQuery AJAX

A JSON file can also be fetched with jQuery AJAX just like a Text file. Let us see 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 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.

fetch json with jquery ajax

Capturing jQuery AJAX Error

You can use the “error” key to call a function in case of receiving some 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: " + status + " " + xhr.status + " " + xhr.statusText)
                },
                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” when you click the button.

DEMO

jQuery AJAX to Call a PHP Page

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.

jQuery ajax call php page

<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>

Before calling the jQuery AJAX method I am validating the email. If the email is in correct syntax only then I call jQuery 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 echo method.

DEMO

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

With jQuery AJAX 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.

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

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.

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 our 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.

DEMO DOWNLOAD

Other related topics in AJAX are –

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.