[jQuery] ajax() Function

The “jQuery.ajax()” function peforms an asynchronous request. The previous post shows the frequently used settings. This post focuses on the function itself and how you can use it.

1. ajax() Function

The “$.ajax()” function is very simple if you understand how to setup settings.

  • jQuery.ajax( url,  settings )
  • jQuery.ajax( settings )

For global settings you can use the “$.ajaxSetup()” function.

  • jQuery.ajaxSetup( options )

 

2. Example

Let’s create a response file first. The data file (data.txt) has “JSON” data.

{ "name" : "Homer", "message" : "I want pizza." }

Here is how you can use the ajax() function.

function onBeforeSend(xhr /*XMLHttpRequest */) {
  return confirm("Do you want to continue");
}
function onSuccess(data, textStatus, xhr) {
  $("#result").text(data.name + " : " + data.message);
}
function onError(xhr,status,error) {
  $("#result").text(status + " - " + error);
}
function onComplete(xhr,status) {
  alert("Completed!!!");
}

function doAjax() {
  $.ajaxSetup({ async:true, cache:false });
  $.ajax("data.txt",
    {
      dataType: "json",
      type: "GET",
      dataFilter: function (data, type) {
        if (type == "json") {
          return data.replace("pizza", "donuts");
        }
        return data;
      },
      success: onSuccess,
      error: onError,
      beforeSend: onBeforeSend,
      complete: onComplete
    }
  );
}

$("document").ready(function () {
  $("#btn").on("click", doAjax);
});

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s