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 browser, 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 useful is the asynchronous nature of the data exchange. Prior to its advent, data was only sent during the client communication phase (when the web page is 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 main method of interacting with the server and the client; it is supported by all modern browsers. There are a number of frameworks and libraries with a higher level API that encapsulate the XMLHttpRequest object, providing an easier interface to hide the complexity of using the object directly.

The client opens a new XMLHttpRequest and requests a web page, just like a normal client call would. This request, however, is typically aimed at a special 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 make sure 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 common 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:

215922 questions
5960
votes
42 answers

How to return the response from an asynchronous call?

I have a function foo which makes an asynchronous request. How can I return the response/result from foo? I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that…
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
4244
votes
8 answers

Why does Google prepend while(1); to their JSON responses?

Why does Google prepend while(1); to their (private) JSON responses? For example, here's a response while turning a calendar on and off in Google Calendar: while (1); [ ['u', [ ['smsSentFlag', 'false'], ['hideInvitations', 'false'], …
Jess
  • 39,842
  • 6
  • 34
  • 51
3020
votes
34 answers

How can I upload files asynchronously?

I would like to upload a file asynchronously with jQuery. $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url:…
Sergio del Amo
  • 71,609
  • 66
  • 148
  • 177
2070
votes
41 answers

How do I format a Microsoft JSON date?

I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like…
Mark Struzinski
  • 31,745
  • 33
  • 103
  • 135
1897
votes
18 answers

Abort Ajax requests using jQuery

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?
lukewm
  • 20,467
  • 6
  • 24
  • 28
1791
votes
35 answers

Disable same origin policy in Chrome

Is there any way to disable the Same-origin policy on Google's Chrome browser?
Landon Kuhn
  • 61,957
  • 42
  • 100
  • 130
1436
votes
33 answers

How to manage a redirect request after a jQuery Ajax call

I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login…
Elliot Vargas
  • 19,101
  • 9
  • 32
  • 36
1255
votes
14 answers

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an item from being created. I've added an Ajax call into this function using jQuery: beforecreate:…
Artem Tikhomirov
  • 20,413
  • 10
  • 43
  • 66
1238
votes
15 answers

How to manually send HTTP POST requests from Firefox or Chrome browser?

I want to test some URLs on a web application I'm working on. For that I would like to manually create HTTP POST requests (meaning I can add whatever parameters I like). Is there any extension or functionality in Chrome and/or Firefox that I'm…
Pascal Klein
  • 20,294
  • 23
  • 79
  • 118
1216
votes
11 answers

Serializing to JSON in jQuery

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this? My specific situation: I have an array defined as shown below: var countries = new Array(); countries[0] = 'ga'; countries[1] = 'cd'; ... and I need to…
Herb Caudill
  • 48,763
  • 38
  • 117
  • 170
1090
votes
25 answers

Is Safari on iOS 6 caching $.ajax results?

Since the upgrade to iOS 6, we are seeing Safari's web view take the liberty of caching $.ajax calls. This is in the context of a PhoneGap application so it is using the Safari WebView. Our $.ajax calls are POST methods and we have cache set to…
user1684978
  • 8,449
  • 3
  • 11
  • 6
1017
votes
20 answers

jQuery AJAX submit form

I have a form with name orderproductForm and an undefined number of inputs. I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm. I suppose…
Nathan H
  • 44,105
  • 54
  • 154
  • 235
911
votes
31 answers

Scroll to bottom of div?

I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck. I am wrapping everything in this div: #scroll { height:400px; overflow:scroll; } Is there a way to keep it scrolled to…
dMix
  • 14,498
  • 17
  • 45
  • 61
855
votes
16 answers

Ajax request returns 200 OK, but an error event is fired instead of success

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event. I tried a lot of things, but I could not figure out the problem. I am adding my code…
Pankaj Mishra
  • 19,129
  • 14
  • 63
  • 102
839
votes
23 answers

How to make an AJAX call without jQuery?

How to make an AJAX call using JavaScript, without using jQuery?
discky
  • 13,001
  • 7
  • 18
  • 11
1
2 3
99 100