Skip to content
Amal Hashim
All posts
Snippet

jQuery Ajax Call

A reusable $.ajax template for calling a JSON service with success and error callbacks.

1 min read#JavaScript#jQuery

A template for a GET call to a JSON service with $.ajax.

js
$.ajax({
   url: GETURL,
   type: "GET",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: successCallback,
   error: errorCallback,
   dataFilter: function (data, type) {
      // ADO.NET Data Services can return invalid JSON,
      // so use a pre-filtering function to sanitise the response
      return data.replace(/\\'/g, "'");
   }
});

function successCallback(result) {
   if (result != null) {
      var data = result["d"][0];
      // data[PROPERTY_NAME] or data[0] etc.
   }
}

function errorCallback(xhr, ajaxOptions, thrownError) {
   alert("Error occurred. Status - " + xhr.status +
      ", Error text - " + thrownError +
      ", Response text - " + xhr.responseText);
}

Replace GETURL with the address of your service. The d wrapper in the result is how ASP.NET and ADO.NET services return their data.