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

How to post the parameter in ajax call of jquery datatable

As of now I am passing parameter along with URL in ajax call of data table. But I want to pass it as POST method, please anyone one help me regarding parameter passing in post method, here's my trial code: // Sending through GET var $table =…
chaya
  • 353
  • 3
  • 7
  • 17
20
votes
3 answers

RxJS Continue Listening After Ajax Error

RxJs stops listening to click events when an inner observable errors (Ajax request). I'm trying to figure out how to keep the event listener hooked to the button click event and gracefully handle the inner ajax error. Here is my example code and a…
20
votes
4 answers

How to checkif there are pending requests (Ajax and its variants) from browser

Some of the sites I deal with have heavy ajax requests. I plan to wait for Ajax request completion before clicking for asserting for element. Currently I use try { if (driver instanceof JavascriptExecutor) { JavascriptExecutor jsDriver =…
raju
  • 4,752
  • 11
  • 56
  • 110
20
votes
4 answers

Img src path with header params to pass

I have an img tag in jsp page where the src path requires header parameters to pass to get the image. How can we achieve it?
Arjun
  • 415
  • 1
  • 5
  • 13
20
votes
2 answers

Best AJAX TreeView

What are some of the better AJAX Treeviews out there that support asynchronous JSON loading. YUI TreeView seems nice, but bloated with tables, etc.
ckarbass
  • 3,539
  • 7
  • 31
  • 43
20
votes
3 answers

Easy way to AJAX WebControls

I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style DIVs. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based…
tags2k
  • 70,860
  • 30
  • 74
  • 105
20
votes
8 answers

Ajax.BeginForm doesn't fire AJAX script, falls back on postback

I will update this problem with the solution, I wanted to include my problem and solution as I wasn't able to find it on Stackoverflow. If you want to jump in with the solution, feel free. I have a newly created 'Empty' MVC5 project created using…
Tentux
  • 704
  • 1
  • 4
  • 13
20
votes
2 answers

Add custom http header to all jQuery AJAX Requests

Point of clarification: I don't have any problem adding a custom header to my jQuery ajax call, I want to have my custom header added to all ajax calls automatically. If you take a look at jquery $.ajax custom http headers issue (not my question),…
Peter
  • 9,445
  • 6
  • 55
  • 103
20
votes
3 answers

How can I make AJAX requests using the Express framework?

I want to send AJAX requests using Express. I am running code that looks like the following: var express = require('express'); var app = express(); app.get('/', function(req, res) { // here I would like to make an external // request to…
codeofnode
  • 15,885
  • 23
  • 74
  • 127
20
votes
2 answers

Rails 4: How to upload files with AJAX

I want to upload files with AJAX. In the past I accomplished this by using the magical jQuery form plugin and it worked great. Currently I'm building a Rails app and trying to do things "The Rails Way" so I'm using the Form Helper and the paperclip…
emersonthis
  • 30,934
  • 52
  • 191
  • 328
20
votes
7 answers

How to create a Youtube style loading bar with Rails 4's Turbolinks?

Is there a way to make a Youtube style loading bar (the inter-page across the top bar) with turbo-links. Turbolinks has loads of different callbacks so you could make a jumpy one across a few steps but is there a way to hook into the progress too?
MintDeparture
  • 5,745
  • 15
  • 76
  • 136
20
votes
2 answers

POST jQuery array to Django

I'm trying to POST a jQuery array of simple numbers to Django, and I really can't make it work. I need a little help on this. I'm getting an Http 500 with the following error: Internal Server Error: /edit_lists/ Traceback (most recent call last): …
jabez
  • 819
  • 1
  • 9
  • 20
20
votes
3 answers

Way to tell if a post came from an ajax call in codeigniter?

I just started using CodeIgniter after using Zend for a while. My new site has a feature where you register through Ajax. In Zend I could use this to check if the incoming POST was through AJAX, and therefore from my…
Ethan
  • 5,498
  • 9
  • 40
  • 49
20
votes
2 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,687
  • 3
  • 27
  • 62
20
votes
6 answers

jquery select2 - not working

I am using select2 plugin(ivaynberg.github.io/select2). I am trying to display a dropdown(select). It is getting all the items in data.php as options. However select2 is meant to be autocomplete plugin and should search for the search term a client…
user2315153
  • 296
  • 1
  • 2
  • 7
1 2 3
99
100