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
22
votes
3 answers

Jquery events not working on ajax loaded content

The below code works. If there is some better way please let me know. If i use the script content which is present in test.html in the main page where I am loading test.html through ajax. The script doesn't work.
Susheel Singh
  • 3,824
  • 5
  • 31
  • 66
22
votes
6 answers

Pass array data from javascript in browser to spring mvc controller using ajax

I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX In javascript, I have var a = []; a[0] = 1; a[1] = 2; a[2] = 3; // how about multiple arrays as well? $.ajax({ type : "POST", url :…
Alfred Zhong
  • 6,773
  • 11
  • 47
  • 59
22
votes
2 answers

What is the X-FB-DEBUG header returned from Facebook?

I'm wondering what the header mentioned above is. It's included in the response when I do JSONP calls to Facebook, or even when I simply access http://static.ak.fbcdn.net/ I haven't found any documentation on facebook, e.g. on…
23tux
  • 14,104
  • 15
  • 88
  • 187
22
votes
5 answers

Jquery getJSON populate select menu question

I am populating a select menu with getJSON. I am wondering if there's a way that I can use jQuery's .each function to bring in these values? Surely there must be an easier way to accomplish this...maybe? PHP file:
Scott
  • 823
  • 4
  • 11
  • 21
22
votes
6 answers

getJSON timeout handling

I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page. So jQuery ajax() function have an timeout variable. But…
pheaselegen
  • 398
  • 1
  • 4
  • 15
22
votes
1 answer

Phonegap-Javascript sending cross-domain ajax request

I'm using PhoneGap and JavaScript to produce an iPhone app. Is it possible to send a cross-domain AJAX (POST) request and download the response as HTML? (ex.: sign into yahoo mail and fetch new mails)
Pharaz Fadaei
  • 1,605
  • 3
  • 17
  • 28
22
votes
1 answer

How to do long-polling AJAX requests in ASP.NET MVC?

Does anyone know how to code up long-polling AJAX requests (for server PUSH notifications) in ASP.NET MVC? Whenever I do it, it seems that only the last browser to open up a window gets the notifications. As if IIS/ASP.NET were canceling the last…
Andrew Arnott
  • 80,040
  • 26
  • 132
  • 171
22
votes
9 answers

Javascript Distributed Computing

Why aren't there any Javascript distributed computing frameworks / projects? The idea seems absolutely awesome to me because: The Client is the Browser Iteration can be done with AJAX Webmasters could help projects by linking the respective…
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
22
votes
6 answers

java.lang.IllegalStateException: CDATA tags may not nest

I've got a problem with an ajax request in a JSF page. When I click on the button, I get this exception: SEVERE: Servlet.service() for servlet Faces Servlet threw exception java.lang.IllegalStateException: CDATA tags may not nest at…
alinoe
  • 221
  • 1
  • 2
  • 3
22
votes
2 answers

javascript: cancel all kinds of requests

My website makes a lot of requests. I often need to cancel all current requests, so that the browser is not blocking relevant new requests. I have 3 kinds of requests: Ajax inserted script-tags (which do JSONP-Communication) inserted image-tags…
Julius Eckert
  • 1,481
  • 4
  • 16
  • 24
22
votes
2 answers

How to debug a failed ajax request in google chrome?

I have a web application that crashes on ajax requests with google chrome (it works with every other web browser it was tested it). After debugging I found that the error is caused by response.responseText being undefined. The xhr object looks like…
zefciu
  • 1,967
  • 2
  • 17
  • 39
22
votes
2 answers

Ajax.BeginForm replaces whole page onchange of a dropdownlist

The purpose I have a simple table listing names (in a partial view), and above it a dropdownlist containing those names. The purpose is to filter the table based on the name which was selected in the dropdownlist. The filtering should happen as soon…
Peter
  • 769
  • 1
  • 9
  • 23
21
votes
14 answers

ASP.NET webforms + ASP.NET Ajax versus ASP.NET MVC and Ajax framework freedom

If given the choice, which path would you take? ASP.NET Webforms + ASP.NET AJAX or ASP.NET MVC + JavaScript Framework of your Choice Are there any limitations that ASP.NET Webforms / ASP.NET AJAX has vis-a-vis MVC?
public static
  • 12,702
  • 26
  • 66
  • 86
21
votes
2 answers

Submit form via AJAX in jQuery

I am using following jQuery code to submit a form via AJAX. jQuery('form.AjaxForm').submit( function() { $.ajax({ url : $(this).attr('action'), type : $(this).attr('method'), dataType:…
Student
  • 1,863
  • 9
  • 37
  • 50
21
votes
4 answers

AJAX (XmlHttpRequest) timeout length by browser

I've been scouring the web trying to find a straight answer to this. Does anyone know the default timeout lengths for ajax request by browser? Also by version if it's changed?
wajiw
  • 12,239
  • 17
  • 54
  • 73
1 2 3
99
100