Asynchronous JavaScript and XML (Ajax) Functionality
Implementing Ajax functionality in your web application allows for asynchronous data retrieval without causing browser crashes or lock-ups. To achieve this, you must utilize callback functions to handle responses.
Below are some examples of Ajax implementations using the XMLHttpRequest Level 2 (xhr2) standard, which is widely supported by modern browsers, including IE10, Android, and iOS.
Simple Ajax GET Function:
// Define a simple function for making GET requests
function ajax(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = callback;
xhr.open('GET', url);
xhr.send();
}
Usage:
ajax(url, callback);
How to Access the Returned Value inside the Callback Function:
function callback(event) {
event.target.response;
this.response;
xhr.response; // if used inline within the ajax function
}
Complex Ajax Function:
// Define a more complex Ajax function with optional parameters
function ajax(url, callback, method, data, uploadFunc, downloadFunc) {
var xhr = new XMLHttpRequest();
if(uploadFunc) { xhr.upload.onprogress = uploadFunc; }
if(downloadFunc) { xhr.onprogress = downloadFunc; }
xhr.onload = callback;
xhr.open(method || 'GET', url);
xhr.send(data || null);
}
Usage:
var formData = new FormData();
formData.append('act', 'get_conv_data');
formData.append('click_id', click_id);
formData.append('server', server);
ajax(ajaxUrl, callback, 'POST', formData);
function callback() {
alert(this.response);
}
Alternatively, you can pass form data directly from HTML:
<form id="form">
<input name="server" value="serverBLABLA">
<input name="click_id" value="click_idBLABLA">
<input name="act" value="get_conv_data">
</form>
JavaScript Code:
ajax(ajaxUrl, callback, 'POST', new FormData(document.getElementById('form')));
function callback() {
alert(this.response);
}
For more information on implementing these functions, refer to this Stack Overflow post.