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
21
votes
1 answer

Passing extra parameter to f:ajax onevent function

In my JSF 2.0 (on JBoss AS 7) project, I would like on my ajax submitted forms to display a little icon status triggered on begin and complete phases, to let the end user know that something is still happening. The primefaces p:ajaxStatus is not…
Xavier Portebois
  • 3,354
  • 6
  • 33
  • 53
21
votes
3 answers

Is it possible to run a HAR archive on google chrome?

Is it possible to a run a HAR file that was generated by chrome? I have exported a ajax request from chrome and changed a parameter and I want to run it again. I'm trying to debug using a problem on my site and this ajax request must be executed on…
Luiz Guilherme
  • 1,601
  • 21
  • 37
21
votes
5 answers

Merge two json objects with jquery

I have two json objects: http://example.com/search.json?section=saloon and http://example.com/search.json?section=coupe I have been looking for a way to combine these two objects into one object. Thanks in advance.
echez
  • 555
  • 3
  • 7
  • 19
21
votes
4 answers

Inspecting large JSON data in Chrome

There is a page on my website that uses jquery AJAX to request JSON data from the PHP backend. I want to view the JSON returned to the browser, and is trying to do so using Chrome browser's Developer tools, under Network> Response. Problem: Although…
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
21
votes
3 answers

Can't dynamically add rows to a in IE?
I have an AJAX application that downloads a JSON object and uses the data to add rows to an HTML
using Javascript DOM functions. It works perfectly... except in Internet Explorer. IE doesn't give any sort of error, and I've verified as best…
Joshua Carmody
  • 13,410
  • 16
  • 64
  • 83
21
votes
1 answer

UIForm with prependId="false" breaks

I have a question about the idea behind the fact, that only UIForm got the attribute prependId. Why is the attribute not specified in the NamingContainer interface? You will now probably say that's because of backward compability but I would…
Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
21
votes
11 answers

Gmail like file upload with jQuery

I would like to upload files just like google mail does. I would want to use jQuery and PHP to do it is there anyway of getting the progressbar etc.? Here I added a video of how google does it.…
Thomaschaaf
  • 17,847
  • 32
  • 94
  • 128
21
votes
6 answers

Trouble with Primefaces 3.0.M2 SelectOneMenu Ajax behavior

I am having trouble with implementing two SelectOneMenu controls, where data in the second one depends on the selection made in the first. This example on the primeFaces showcase is almost the same as what I want to implement:…
agileai
  • 211
  • 1
  • 2
  • 7
21
votes
3 answers

nodejs express, ajax posting w/ jquery and receiving response

Having some trouble getting express to respond properly to my jquery ajax request. The actual posting is working fine, but no matter what I try I cant seem to actually get a data response from my app that I can use. At first it was just posting and…
thrice801
  • 1,671
  • 5
  • 23
  • 31
21
votes
9 answers

jQuery load to variable

I need insert result from jQuery load to variable. Content of elemtent with id test on page ajax.html. $('#result').load('ajax.html #test');
honzahommer
  • 839
  • 3
  • 10
  • 15
21
votes
7 answers

Is it possible to have the url change while you scroll down a single page

Is it possible to have the url change while you scroll down a single page with ajax? I have a website all on one page and want to have this effect. example: www.blablabla.com/blog user scroll down... www.blablabla.com/blog/entry-name I know about…
eptype
  • 211
  • 1
  • 2
  • 4
21
votes
11 answers

Debugging Ajax code with Firebug

I've a couple of problems debugging code returned in an Ajax call - specifically, a function returned in json (errors don't get trapped in Firefox) - up to the point where I started debugging these problems in Internet Explorer (I think it's a…
Erico Lendzian
  • 333
  • 1
  • 3
  • 9
21
votes
6 answers

Refresh a table with jQuery/Ajax every 5 seconds

So I have a table pulling information from a database and I was wondering how I could make it refresh its information without reloading the whole page.
Ben Cobbold
  • 231
  • 1
  • 2
  • 4
21
votes
1 answer

How is pjax working?

I just discovered pjax and I find it completly awesome. If I understand it correctly, it's AJAX, but without its problems (fully degradable, the URL and the title of the page is changing when using it, compatible with search bots...). But I am very…
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
21
votes
4 answers

stop scrolling to top after AJAX request

Possible Duplicate: How do I stop a web page from scrolling to the top when a link is clicked that triggers javascript? my browser scrolls to top after ajax request then i use $('html, body').animate({ scrollTop: $('#loadMore').offset().top },…
Miroo
  • 795
  • 3
  • 13
  • 35
1 2 3
99
100