Home > UI/UX Development > jQuery > Common jQuery Ajax methods and options

Common jQuery Ajax methods and options

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

  1. Go to Ajax Methods
  2. Go to Option Parameter

Ajax and jQuery makes life easier for developer 🙂

Ajax Methods

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.

Example Code of PHP:- Some security reason I can’t’ upload php file, Please find reference below. 

Output of $.ajax() core request 

Ajax Core Output

$.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 

$.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 

$.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.

getScript cache

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 

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.

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.

$.load() Example HTML Code 

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.

Option Parameter

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.

This Article is TAGGED in , , , . BOOKMARK THE permalink.

Avatar photo
Chintan Upadhayay
I am a senior web developer with more than 4+ years experience in WordPress, PHP, MySQL, HTML, CSS, jQuery and other web technologies. I am the beginner in SharePoint and Learning SharePoint.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">