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

Enter your email address

Subscribe to this blog and receive notifications of new posts by email. Join over 81,000 other subscribers

Don't worry we won't spam.

subscribers