This post was most recently updated on July 29th, 2024
In the previous article, we learned about event.preventDefault() vs event.stopPropagation() vs return false. In this article, we will cover the most basic methods/function used in jQuery when dealing with Ajax.
Ajax ( Asynchronous JavaScript and XML ) it allows web pages to change/update data asynchronously with a web server without reloading the page.
Table of Contents
- Go to Ajax Methods
- Go to Option Parameter
Ajax and jQuery makes life easier for developer 🙂
The methods are listed in the following table are common ajax methods, that require less code compare to standard ajax call.
Method | Description |
$.ajax() | $.ajax() is core and heart of all ajax methods. It perform an async request |
$.get() | Perform a GET request on provided URL |
$.post() | Perform a POST request on provided URL |
$.getScript() | getScript method load and execute a script file |
load() | Load any static and dynamic data from server and add into selected element |
Please check out the tutorial for the detailed explanation and understand about ajax common method and option.
$.ajax()
jQuery offers a primary method which called $.ajax(). It is a core method and heart of all other methods like $.get(), $.post(). The jQuery.ajax() function is used to perform an asynchronous HTTP request. The syntax of this function is shown below:
jQuery.ajax( url [, options] )
The URL parameter is a string containing URL and options are an object which is containing the configuration settings for the ajax request. Options/Settings are the pairs of key/value. Let’s look below ajax core example where I show URL and Settings.
An ajax HTTP request goes to the given URL with some contact data, I used GET method, set false async option and used success, error and complete function with other option. Expect URL, all other settings are optional but I used here to understand ajax setting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
//$.ajax() method $.ajax({ // The URL for the request url: '<YOUR_DOMAIN>/demo_core_ajax.php', // The data to send to the server // Key value pair of data (It will be converted to a query string) data: {//firstName and lastName is getting dynamic value Fname: firstName, Lname: lastName }, // Whether this is a POST or GET request type: 'GET', //Default is true, It first complete the this request and then go for another request, async: false, // The type of data we expect back,It can be "xml", "html", "text", "script", "json", "jsonp" dataType: 'json', // The type of data which will send to the server contentType: 'application/x-www-form-urlencoded; charset=UTF-8', //An object of additional header key/value pairs to send with request to the server,Check in Header requests under xhr network headers: {'x-my-custom-header': 'some value'}, //Set a timeout for the request in millisecond timeout: 2000, //Code to run if the request succeeds; // the response is passed to the function success: function (data) { $('.ajaxCoreMSG').html("Hello I am " + data.Fname + " " + data.Lname); }, // code to run if the request fails; // the raw request and status codes are // passed to the function error: function (xhr, status) { alert('Sorry, there was a problem!'); }, // code to run regardless of success or failure complete: function (xhr, status) { alert('The request is complete!'); } }); |
Example Code of PHP:- Some security reason I can’t’ upload php file, Please find reference below.
1 2 3 4 |
<?php //We can use send data to perform any query or logic echo json_encode($_GET); die(0); |
Output of $.ajax() core request
$.get()
$.get() perform a GET request on provided URL and the optional data.It can also run the callback function when a request has been completed. It is a shorthand method. The syntax of this function is shown below:
jQuery.get( url [, data ] [, success ] [, dataType ] )
The parameters are described below:
- url : The string containing url of the request.
- data : A optional string or a plain object that send to the server with a request.
- success : Run the callback function when a request has been completed.
- dataType : The data type of the expected from the server. In an example, I used “text”. This can also be a string of multiple, space-separated values. For example, if you want a text response to be treated as XML, use “text xml” for the dataType.
In $.get() method you can share your requested URL because given the set of parameters is appended as a query string in the requested URL so the result is shown as per parameters.
$.get() Example Code
1 2 3 4 5 6 7 8 9 10 |
//$.get() method $('.getMethod').on('click', function () { var data = {}; $.get( "<YOUR_DOMAIN>/ajax_get_method.txt", data, function (data, status) { //Callback Function $('.getMethodMSG').html("Data: " + data + "\nStatus: " + status); }, "text"); }); |
$.post()
$.post() perform a POST request on provided URL. For a POST request, it will be sent as form data not append data as $.get() method do. jQuery provides the helpful .serialize() method for taking form input and converting it to a query string format.
POST should be used if our request has the potential to cause a change in the server-side state and it much safer then GET request. The syntax of this function is shown below:
jQuery.post( url [, data ] [, success ] [, dataType ] )
We already discuss the parameters for $.get() method those are the same for the $.post() method. So I won’t repeat them here :-).
$.post() Example Code
1 2 3 4 5 6 7 8 9 10 |
//$.post() method $('.postMethod').on('click', function () { var data = {}; $.post( "<YOUR_DOMAIN>/ajax_get_method.txt", data, function (data, status) { //Callback Function $('.postMethodMSG').html("Data: " + data + "\nStatus: " + status); }, "text"); }); |
$.getScript()
GetScript method load and execute a JavaScript file from the server using a GET HTTP request. By default, it has URL and Success function. Run the callback function when a request has been completed. The callback is fired once the script has been loaded but not necessarily executed.
The interesting thing about getScript is, It makes every request cache, this appends a timestamped eg (“?_=1511521879902”) query parameter to the request URL to ensure that the browser downloads the script each time it is requested.
You can change this using $.ajaxSetup() but it’s not recommended to override because this can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings of the call.
The syntax of this function is shown below:
jQuery.getScript( url [, success ] )
$.getScript() Example Code
1 2 3 4 5 6 7 8 |
//$.getScript() method //It's not recommended $.ajaxSetup({//Default is false it wil look like in your "demo_ajax_script.js?_=1511520846145" cache: true //This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. }); $.getScript("<YOUR_DOMAIN>/demo_ajax_script.js", function (data, status) { $('.getScriptMethodMSG').html("Data: " + data + "\nStatus: " + status); }); |
let’s move our attention to the next method.
$.load()
This is simplest way to load data from the server, $.load() sets the HTML contents of the matched element to the returned data.
The syntax of this function is shown below:
.load( url [, data ] [, complete ] )
Loading Page Fragments
Imagine you have an element in your website having an id option. We want to retrieve only the content inside this element because the other parts of the layout don’t change, so they don’t need to be loaded. It retrieves the content of load_ajax_method.html, but then jQuery parses the returned document to find the element with an ID of ul. It fetches only that given element part of the document and returns only option data.
1 2 3 4 |
//load() method $('.loadMethod').on('click', function () { $(".pageWrap").load("<YOUR_DOMAIN>/load_ajax_method.html #option"); }); |
In this below example If no element is matched by the selector, if a document does not contain an element with class=”pageWrap” ajax call will not be sent.
1 2 3 4 |
//load() method $('.loadMethod').on('click', function () { $(".pageWrap").load("http://localhost/projects/ajax_eample/load_ajax_method.html"); }); |
$.load() Example HTML Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<div class="pageWrap" style="border: 1px solid #222; width:50%; text-align: left; margin:0; padding: 5px 10px; "> <p>It will return only list of option ID element.</p> <h2>Ajax Shorthand Method</h2> <ul id="methods"> <li>$.ajax()</li> <li>$.get()</li> <li>$.post()</li> <li>$.getScript() </li> <li>load()</li> </ul> <h2>Ajax Option</h2> <ul id="option"> <li>url</li> <li>type</li> <li>async</li> <li>data</li> </ul> </div> |
Above is the convenient ajax method and we can achieve our goal with just one line of code.
let’s move our attention to the next point.
There are many options parameter in $.ajax() here are several that you will use frequently. A set of key/value pairs that configure the Ajax request. An optional setting which we send with the request. Options/Settings are the pairs of key/vale.
Option | Type | Description |
url | String | The string containing url of the request. To make an ajax request we need a URL. |
type | String | The type of request GET, POST, PUT and DELETE. Default to “GET” |
async | Boolean | Set to be false to make a synchronous request. It first completes the current request and then goes for another request. Note, a synchronous request will lock the browser. Default to “TRUE”. |
data | PlainObject or String or Array | The data to send server while performing the ajax request. This either can be object or query string like “Fname=John&Lname=Smith” |
contentType | Boolean or String | The type of data which will send to the server. Such as “application/x-www-form-urlencoded” |
dataType | String | The type of data expected back from the server. It can be “xml”, “html”, “text”, “script”, “json”, “jsonp” |
cache | Boolean | It cache the requested page. This appends a timestamped eg (“?_=1511521879902”) query parameter to the request URL. |
timeout | Number | Set a timeout for the request in a millisecond. This setting overrides the global settings. |
headers | PlainObject | An object to send additional headers to send to the server. An object of additional header key/value pairs to send with request to the server.such as headers: {‘x-my-custom-header’: ‘some value’} |
success | Function | After the success of the callback request. |
error | Function | This method call when the request failed. |
complete | Function | After the request is complete the callback function ( both call request success or failure). |
jsonpCallback | String or Function | Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. |
crossDomain | Boolean | If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. |
jsonp | String or Boolean | Override the jsonp callback function name in jsonp request. |
See the DEMO.
Source: jQuery Ajax
Hope you find it helpful. If you liked this article, then please share and comment.