jQuery AJAX Example – Calling a C# Function With jQuery AJAX [With Code]

jQuery AJAX Example – Calling a C# Function With jQuery AJAX [With Code]

In this jQuery AJAX Example, you’ll learn about one of jQuery’s most powerful features — performing an Asynchronous HTTP Request, commonly known as AJAX (Asynchronous JavaScript and XML). With AJAX, you can update specific sections of your web page without reloading it entirely, making your application faster, more lightweight, and significantly more interactive.

In this tutorial, I’ll walk you through creating a simple yet powerful jQuery AJAX example that demonstrates how easily it can be implemented in your web application. Along the way, I’ll also cover jQuery Validation techniques to prevent users from entering invalid values into the text boxes.

jQuery AJAX Example Application

I will create this application in ASP.NET Web Forms with C# as the programming language. I will be making AJAX call using jQuery AJAX method.

no page refresh in jquery ajax

Now coming to the development part, here I have two text boxes, one for name and other for email, and a submit button.

When the user fills in both text boxes and clicks the button, an AJAX request is sent to the C# function on the server — all without triggering a page postback.

The work of this C# function is to store the two text boxes information in the database.

At the end, the function returns the success or failed message, depending up on whether the information is saved successfully in the database or not.

The HTML of the Web Page and jQuery AJAX Method is given below:

Page HTML

<h1>Subscribe To Our Newsletter</h1>
<div id="errorDiv"></div>
<table>
    <tr>
        <td>Name:-</td>
        <td>
            <input type="text" id="nameInput"/></td>
    </tr>
    <tr>
        <td>Email:-</td>
        <td>
            <input type="text" id="emailInput" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" id="submitButton" value="Submit"/></td>
    </tr>
</table>
<img src="Image/loading.gif" id="loadingImg" hidden="hidden"/>

The jQuery AJAX Method Calls the Below C# Function

[WebMethod]
public static string Subscribe(string name, string email)
{
    //Insert it to our database
    return "thanks "+name+", your email "+email+" is subscribed to our newsletter.";
}
Why I used [WebMethod] in this jQuery AJAX Example?

It is an attribute that can be applied to certain functions in C#. It is necessary that this method should be static and must have the attribute of [WebMethod] so that it can be called with the jQuery AJAX Method.

jQuery AJAX Method Code

$(document).ready(function () {
    $("#submitButton").click(function (e) {
        var result = ValidateAll();
        if (result == true) {
            $.ajax({
                type: "POST",
                url: "jquery-ajax.aspx/Subscribe",
                contentType: "application/json; charset=utf-8",
                data: '{"name":"' + $("#nameInput").val() + '","email":"' + $("#emailInput").val() + '"}',
                dataType: "json",
                success: function (msg) {
                    if (msg.d) {
                        $("#errorDiv").html(msg.d);
                    }
                },
                error: function (req, status, error) {
                    alert("Error try again");
                }
            });
        }
        return false;
    });
});
  • The jQuery AJAX method is called in the submit button click event.
  • I have given the C# function’s location to the url field, and passed the values of the two text boxes in the function parameter by using the data field.
  • Finally, the returned message (that is returned by the C# function), is shown on the errorDiv.

jquery ajax example

Please note that return false is added at the end of the button’s click event handler. This ensures that clicking the button does not trigger a page postback, keeping the entire interaction asynchronous.

Showing Loading Image During jQuery AJAX Calls

You can use jQuery AJAX Events to display a loading image whenever an jQuery AJAX Call is made, and automatically hide it once the call completes.

For this we can use the ajaxStart and ajaxStop functions. The updated code is given below:

$(document).ready(function () {
    $(document).ajaxStart(function () {
        $("#loadingImg").show();
    });

    $(document).ajaxStop(function () {
        $("#loadingImg").hide();
    });

    //jQuery AJAX Method
});

Kindly check the below link for this tutorial:

DOWNLOAD

The whole process is explained on the below image:

asp.net web forms jquery ajax flow

Conclusion

I hope you learned this jQuery AJAX Example and now can go on and use it in your websites. The jQuery AJAX is very useful for making complex looking things in a better manner.

With it, you will reduce your code’s length and will make your web application faster, manageable and lighter. The jQuery AJAX will also benefit your server by giving it less load, and so it is a win-win situation for both website administrators and their customers.

More jQuery Tutorial

1. How to Make Sticky Ads with jQuery Effortlessly.
2. Creating jQuery Expand Collapse Panels In HTML.

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