Questions tagged [ajax]

AJAX (Asynchronous JavaScript and XML) is a technique for creating interactive website user interfaces without the traditional web page refresh or reload. It uses asynchronous data exchange between client and server to update displayed information and respond to user interactions seamlessly. Include additional tags for programming languages, libraries, frameworks, web browsers, protocols and other environmental information.

stands for Asynchronous and .

While not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that described an approach to using a number of existing technologies together, including: / , , , the , , , and most importantly the XMLHttpRequest object. uses the XMLHttpRequest (abbreviated ) API to manage requests from inside the code.

What makes so valuable is the asynchronous nature of the data exchange. Before its advent, data was only sent during the client communication phase (when the web page was first requested). This meant that all data had to either be loaded when the page was requested, or the user interaction would be a series of HTML requests to the server with page refreshes. Each HTML request would provide additional information as part of the URL or as data in a form field with state data often kept as hidden field data. This second alternative used a series of GET or POST operations (i.e., load page, change data, post data, load page, etc.), resulting in the displayed page being refreshed, providing a choppy user experience and possible security issues.

Neither loading an entire data set into the client nor reloading the base page with each GET or POST request was cheap in terms of resources. changed the web model by using JavaScript to asynchronously load data into the client as the data was needed.

The XMLHttpRequest object is the primary method of interacting with the server and the client; it is supported by all modern browsers. There are several frameworks and libraries with a higher level API that encapsulate the XMLHttpRequest object, providing a more straightforward interface to hide the complexity of using the object directly.

The client opens a new XMLHttpRequest and requests a web page, just like a regular client call would. This request, however, is typically aimed at a particular page that loads only data to be processed by JavaScript. As such, the data that needs to be exchanged can be limited to just what is necessary for that particular function, saving time, memory and bandwidth. Because it is asynchronous, this interaction does not have to block any other actions being done on the web page, and it lets the client/browser act more like a local desktop program with the website, exchanging data as needed without reloading any other resources.

Although the "X" in stands for , any type of data can be sent and received. (JavaScript Object Notation) has replaced as the data interchange format of choice. A major reason for using JSON is that JavaScript natively parses JSON text, while XML must be parsed by a much slower and cumbersome set of client libraries. Today, with the help of new responseType objects (ArrayBuffer, Blob, etc.), you can even request binary files via XMLHttpRequest and build much stronger and fully-featured web apps.

When XMLHttpRequest is used directly, the code must handle the communications layer and wait for the request response to be complete. This is shown in the code example below starting with the line if (xmlhttp.readyState == 4 && xmlhttp.status == 200). Since this callback function will be called every time the client receives a packet from the server, this test is needed to ensure the request state is complete and a valid 200 response is received before processing the response.


AJAX Example 1:

var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        //stuff to do with response text (xmlhttp.responseText)
    }
}
xmlhttp.open("GET", "url", true);
xmlhttp.send();

AJAX Example 2:

function (url, params) {
    // IE 5.5+ and every other browser
    var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');

    xhr.open("POST", url, true);

    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    xhr.setRequestHeader("Accept", "application/json");
    xhr.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (this.status >= 200 && this.status < 400) {
                console.log(JSON.parse(this.responseText));
            }
        }
    }
    xhr.send(params);
    xhr = null;
},

Because needing to test the status adds some complexity to , there are many libraries that will handle this interaction for you. Below is an example of using a standard library, and shows how it simplifies


jQuery AJAX Example:

$.ajax({
    url: "url",
    context: document.body
}).done(function() {
    //stuff to do with response text
});

As of Chrome 42, Edge 14 and Firefox 39/52, there is a new API called fetch that drastically simplifies in browsers. There is no support for Internet Explorer. fetch is Promised based.

Fetch AJAX example:

fetch('/url')
    .then(res => res.json())
    .then(jsonData => console.log(jsonData));

fetch('/url', { method: 'POST', body: JSON.stringify({id: 1}), })
    .then(res => res.json())
    .then(jsonData => console.log(jsonData));

Axios AJAX example:

Axios is a Promise based HTTP client for the browser and Node JS.

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

List of AJAX frameworks:

  1. jQuery UI
  2. MooTools
  3. Prototype
  4. YUI Library
  5. ASP.NET AJAX
  6. Spry framework
  7. Dojo Toolkit
  8. Ext JS
  9. Backbone.js
  10. AngularJS
  11. Unified.JS

Resources:

221904 questions
855
votes
26 answers

jQuery Ajax File Upload

Can I use the following jQuery code to perform file upload using POST method of an ajax request ? $.ajax({ type: "POST", timeout: 50000, url: url, data: dataString, success: function (data) { alert('success'); …
Willy
  • 9,681
  • 5
  • 26
  • 25
802
votes
21 answers

jQuery Ajax error handling, show custom exception messages

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message? For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");, I want to…
None
758
votes
22 answers

Wait until all jQuery Ajax requests are done?

How do I make a function wait until all jQuery Ajax requests are done inside another function? In short, I need to wait for all Ajax requests to be done before I execute the next. But how?
lejahmie
  • 17,938
  • 16
  • 54
  • 77
756
votes
17 answers

jQuery Ajax POST example with PHP

I am trying to send data from a form to a database. Here is the form I am using:
Thew
  • 15,789
  • 18
  • 59
  • 100
736
votes
4 answers

Updating address bar with new URL without hash or reloading the page

I either dreamt about chrome (dev channel) implementing a way to update the address bar via javascript (the path, not domain) without reloading the page or they really have done this. However, I can't find the article I think I read. Am I crazy or…
David Murdoch
  • 87,823
  • 39
  • 148
  • 191
699
votes
27 answers

Response to preflight request doesn't pass access control check - No 'Access-Control-Allow-Origin' header

I'm getting this error using ngResource to call a REST API on Amazon Web Services: XMLHttpRequest cannot load http://server.apiurl.com:8000/s/login?login=facebook. Response to preflight request doesn't pass access control check:…
Andre Mendes
  • 7,307
  • 4
  • 14
  • 24
697
votes
7 answers

In MVC, how do I return a string result?

In my AJAX call, I want to return a string value back to the calling page. Should I use ActionResult or just return a string?
user67033
  • 15,945
  • 6
  • 21
  • 11
688
votes
13 answers

Send POST data using XMLHttpRequest

I'd like to send some data using an XMLHttpRequest in JavaScript. Say I have the following form in HTML:
Jack Greenhill
  • 10,240
  • 12
  • 38
  • 70
634
votes
7 answers

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

I've seen a couple questions around here like How to debug RESTful services, which mentions: Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST. I've also heard that browsers support…
John Millikin
  • 197,344
  • 39
  • 212
  • 226
627
votes
13 answers

Sending multipart/formdata with jQuery.ajax

I've got a problem sending a file to a serverside PHP-script using jQuery's ajax-function. It's possible to get the File-List with $('#fileinput').attr('files') but how is it possible to send this Data to the server? The resulting array ($_POST) on…
zoku
  • 7,056
  • 3
  • 20
  • 27
614
votes
17 answers

How do I send a cross-domain POST request via JavaScript?

How do I send a cross-domain POST request via JavaScript? Notes - it shouldn't refresh the page, and I need to grab and parse the response afterwards.
Ido Schacham
  • 6,189
  • 3
  • 17
  • 7
583
votes
11 answers

How can I detect changes in location hash?

I am using Ajax and hash for navigation. Is there a way to check if the window.location.hash changed like this? http://example.com/blah#123 to http://example.com/blah#456 It works if I check it when the document loads. But if I have #hash based…
MilMike
  • 12,571
  • 15
  • 65
  • 82
567
votes
8 answers

How to send FormData objects with Ajax-requests in jQuery?

The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. This interface enables appending File objects to XHR-requests (Ajax-requests). Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used…
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
536
votes
5 answers

jQuery: Return data after ajax call success

I have something like this, where it is a simple call to a script that gives me back a value, a string.. function testAjax() { $.ajax({ url: "getvalue.php", success: function(data) { return data; } }); } but if…
Francesco
  • 24,839
  • 29
  • 105
  • 152
536
votes
21 answers

How can I post data as form data instead of a request payload?

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data". How can…
mjibson
  • 16,852
  • 8
  • 31
  • 42