Saturday, 19 August 2017

JQuery: Common method to make jQuery ajax calls

In this tutorial I am going to write a common js function that you can use to make jquery's ajax requests. Check out the following code sample.


Step 1: Copy and paste the following code in your html file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
//Common function to make ajax calls.
 function makeAjaxCall(method, url, data, headers, dataType, successCallback, errorCallback) {
        $.ajax({
            type: method,
            url: url,
            headers: headers,
            data: data,
            dataType: dataType,
            cache: false,
            success: function (response) {
                successCallback(response);
            },
            error: function (errorResponse) {
                errorCallback(errorResponse);
            }
        });
    }

//Usage:
makeAjaxCall("Get", "/api/getData", {id:1},{ "content-type": "application/json" }, "json",
        function (response) {
            //to do: Handle success response
        },
        function (error) {
            //Handling error response
            var errorMessage;

            if (error.responseText) {
                errorMessage = error.responseText;
            }
            else if (error.statusText) {
                errorMessage = error.statusText;
            }
            else {
                errorMessage = "Error";
            }
            errorMessage += " " + error.status;
            alert(errorMessage);
        });
</script>

No comments:

Post a Comment