AJAX

31 Best AJAX Interview Questions and Answers -[Asynchronous JavaScript and XML]

What is AJAX and how does it work?
The AJAX stands for “Asynchronous JavaScript and XML” and AJAX is a technique to creating interactive web applications and allows us to send and receive data asynchronously without refreshing the web page.

The XMLHttpRequest object is part of a technology called AJAX.

AJAX is very faster and easy, we can implement AJAX in a meaningful manner.

It is a group of related technologies looks like,
a)     HTML/XHTML and CSS
b)     DOM
c)      XML or JSON
d)     XMLHttpRequest
e)     JavaScript

The AJAX was popular in 2005 by Google, with Google Suggest.

Syntax - The parameters specify one or more name/value pairs for the AJAX request.
$.ajax({name:value, name:value, ... })


Why do you use Ajax?
The AJAX stands for “Asynchronous JavaScript and XML” and AJAX is a technique to creating interactive web applications and allows us to send and receive data asynchronously without refreshing the web page.

The AJAX technology used by
a)     Google,
b)     Facebook,
c)      Twitter etc.

Is Ajax still in use?
Yes! AJAX (Asynchronous JavaScript and XML) is used all the time in web pages. It is still the primary way that JavaScript in a web page makes an in-page request to a server.

Is Ajax considered a programming language?
The AJAX (Asynchronous JavaScript and XML) is not a programming language or a tool, but a concept.
The AJAX is a client-side script that communicates to and from a server/database without the need for a post-back or a complete page refresh.
Which are the two methods used for cross domain AJAX calls?
There are two methods used to transfer data between the two more security domains:
1)      CORS  (Cross Origin Resource Sharing) - It works with the HTTP web browsers
2)      JSONP ( JSON with Padding) - It works with the HTTP GET and on legacy browsers

What are the technologies used by AJAX?
1)      HTML/XHTML and CSS
2)      DOM
3)      XML
4)      XMLHttpRequest
5)      JavaScript

What is JSON in AJAX?
The JSON (Asynchronous JavaScript and XML) is abbreviated as JavaScript Object Notation.

The JSON (Asynchronous JavaScript and XML) is a safe and reliable data interchange format in JavaScript, which is easy to understand for both users and machines.

We well know $.Ajax () is call asynchronously by nature but problem is that multiple (>1000 calls) Async AJAX calls on a single page.

$(function () {
  $.ajax({
      type: "GET",
      url: "https://api.github.com/users/anilsingh581",
      success: function (data) { alert(data); }
  });

  $.ajax({
      type: "GET",
      url: "https://api.github.com/users/anilsingh5812",
      success: function (data) { alert(data); }
  });

  $.ajax({
      type: "GET",
      url: "https://api.github.com/users/anilsingh5813",
      success: function (data) { alert(data); }
  });
});


But its display error:  err_insufficient_resources when using chrome any hints.

The solution of above problem is:  $.when () method
//The multiple AJAX requests by using $.when()
$.when(
  $.ajax("https://api.github.com/users/anilsingh581"),
  $.ajax("https://api.github.com/users/anilsingh582"),
  $.ajax("https://api.github.com/users/anilsingh583"),
  $.ajax("https://api.github.com/users/anilsingh584")
  )
  .done(function (data1, data2, data3, data4) {
      //All AJAX requests are finished.
      alert(data1)
      alert(data2)
      alert(data3)
      alert(data4)
  });


OR
$.when($.ajax("/pageurl1.aspx"), $.ajax("/pageurl2.aspx"), $.ajax("/pageurl3.aspx")).then(mySuccess, myFailure);

var mySuccess = function (result) {
  console.log(result);
}

var myFailure = function (result) {
  console.log(result);
}

The AJAX stands for “Asynchronous JavaScript and XML” and AJAX is a technique to creating interactive web applications and allows us to send and receive data asynchronously without refreshing the web page.

The XMLHttpRequest object is part of a technology called AJAX.
AJAX is very faster and easy, we can implement AJAX in a meaningful manner.

Advantages:-
1)      Minimal Data Transfer
2)      An asynchronous call by XMLHttpRequest and it is hold and wait process.
3)      Reduce the traffic travels between the client and the server and the response time is faster so increases performance and speed.
4)      Better responsive and interactivity and faster page renders and improved response times.
5)      Supports almost all modern browsers.
6)      Easy Navigation.
7)      Open source JavaScript libraries available for AJAX support like JQuery, etc.

Disadvantages:-
1.      Insecure and increment the load on web server.
2.      All files are downloaded at client-side.
3.      Browser compatibility issues accrued.
4.      The search engines are not crawling AJAX generated content that means Google can’t index AJAX pages.
5.      AJAX does not play well in encrypted environments.
6.      The server information can't be accessed using AJAX.
7.      Data of all requests is URL encoded and causes increases the size of the request.
8.      ActiveX requests are enabled only in Internet Explorer and newer latest browser.

Example for calling “Synchronous” and “Asynchronous” Requests -
//AJAX Synchronous and Asynchronous Requests
//#REGION NAMESPACE
var demo = demo || {};
//#ENDREGION

demo.ajax = demo.ajax || (function () {

    var getBaseURL = function () {
        var currentBaseURL = location.protocol + "//" + location.hostname +
            (location.port && ":" + location.port) + "/";
        return currentBaseURL;
    };

    var baseURL = getBaseURL();
    var request_token;

    var ajaxAsyncCall = function (requestURL, typeGP, inputs, request_token) {

        $.ajax({
            url: requestURL,
            type: typeGP,
            contentType: "application/json; charset=utf-8",
            data: inputs,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Request_Token", request_token)
            },
            async: true,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null) {
                    if (data.Code == "OK") {
                        alert("Success");
                        return false;
                    }
                    else if (data.Code == "ERROR") {
                        alert('Error - ' + data.Message);
                        return false;
                    }
                }
            }
        });
    };

    var ajaxSyncCall = function (requestURL, typeGP, inputs, request_token) {

        $.ajax({
            url: requestURL,
            type: true,
            contentType: "application/json; charset=utf-8",
            data: inputs,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Request_Token", request_token)
            },
            async: false,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null) {
                    if (data.Code == "OK") {
                        alert("Success");
                        return false;
                    }
                    else if (data.Code == "ERROR") {
                        alert('Error - ' + data.Message);
                        return false;
                    }
                }
            }
        });
    };

    return {
        baseURL:baseURL,
        ajaxAsyncCall: ajaxAsyncCall,
        ajaxSyncCall: ajaxSyncCall
    }
})();

//Use of common Synchronous and Asynchronous methods.

//GET CUSTOMERS LIST WITH SYNC CALL.
demo.ajax.ajaxSyncCall(demo.ajax.baseURL + "API/Users/GetUsersRequest", 'GET', null, function (data) {
    if (data != undefined) {
        successGetCustomers(data);
    }
}, null);

//GET CUSTOMERS LIST WITH ASYNC CALL.
demo.ajax.ajaxAsyncCall(demo.ajax.baseURL + "API/Users/GetUsersRequest", 'GET', null, function (data) {
    if (data != undefined) {
        successGetCustomers(data);
    }
}, null);

//Success Method
var successGetCustomers = function (data) {
    if (data) {
        console.log(data);
        //TODO: As PER YOU!
    }
};

What Is Asynchronous Request in AJAX?
The Asynchronous Request non-blocking the client DOM/browser until your operations is completed and only initiates the operations. It is a backgrounds process.

The Asynchronous Request is not hold and waits process and it is an asynchronous call and the asynchronous calls do not wait for a response to close the socket.

The Asynchronous call are using when requests are not depend to each other request’s responses.
The callback server must be available or the response will be failed.

The operations (send, receive, and reply) will be synchronous or asynchronous.
By default, the $.ajax request in jQuery is set to asynchronous and we can set (async: false) for synchronous operations otherwise (async: true).

Example looks like
//AJAX Synchronous and Asynchronous Requests.
//#REGION NAMESPACE
var demo = demo || {};
//#ENDREGION

demo.ajax = demo.ajax || (function () {

    var getBaseURL = function () {
        var currentBaseURL = location.protocol + "//" + location.hostname +
            (location.port && ":" + location.port) + "/";
        return currentBaseURL;
    };

    var baseURL = getBaseURL();
    var request_token;

    var ajaxAsyncCall = function (requestURL, typeGP, inputs, request_token) {

        $.ajax({
            url: requestURL,
            type: typeGP,
            contentType: "application/json; charset=utf-8",
            data: inputs,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Request_Token", request_token)
            },
            async: true,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null) {
                    if (data.Code == "OK") {
                        alert("Success");
                        return false;
                    }
                    else if (data.Code == "ERROR") {
                        alert('Error - ' + data.Message);
                        return false;
                    }
                }
            }
        });
    };

    var ajaxSyncCall = function (requestURL, typeGP, inputs, request_token) {

        $.ajax({
            url: requestURL,
            type: true,
            contentType: "application/json; charset=utf-8",
            data: inputs,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Request_Token", request_token)
            },
            async: false,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null) {
                    if (data.Code == "OK") {
                        alert("Success");
                        return false;
                    }
                    else if (data.Code == "ERROR") {
                        alert('Error - ' + data.Message);
                        return false;
                    }
                }
            }
        });
    };

    return {
        baseURL:baseURL,
        ajaxAsyncCall: ajaxAsyncCall,
        ajaxSyncCall: ajaxSyncCall
    }
})();

//Use of common Synchronous and Asynchronous methods
//GET CUSTOMERS LIST WITH ASYNC CALL.
demo.ajax.ajaxAsyncCall(demo.ajax.baseURL + "API/Users/GetUsersRequest", 'GET', null, function (data) {
  if (data != undefined) {
      successGetCustomers(data);
  }
}, null);

var successGetCustomers = function (data) {
  if (data) {
      console.log(data);
      //TODO: As PER YOU!
  }
};

What Is Synchronous Request in AJAX?
The Synchronous Request blocks the client DOM/ browser until your operations is completed.

It is basically hold and wait process. The second process will execute after first one is completed and when a synchronous call occurred that time the DOM/browser both are blocked.

A Synchronous call opens a socket and waits for a response before closing the socket.
The operations (send, receive, and reply) will be Synchronous or Asynchronous.

The every blocking operation is not synchronous operations and it may be other operations.
By default, the $.ajax request in jQuery is set to asynchronous and we can set (async: false) for synchronous operations otherwise (async: true).

 The Example looks like
//AJAX Synchronous and Asynchronous Requests.
//#REGION NAMESPACE
var demo = demo || {};
//#ENDREGION

demo.ajax = demo.ajax || (function () {

    var getBaseURL = function () {
        var currentBaseURL = location.protocol + "//" + location.hostname +
            (location.port && ":" + location.port) + "/";
        return currentBaseURL;
    };

    var baseURL = getBaseURL();
    var request_token;

    var ajaxAsyncCall = function (requestURL, typeGP, inputs, request_token) {

        $.ajax({
            url: requestURL,
            type: typeGP,
            contentType: "application/json; charset=utf-8",
            data: inputs,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Request_Token", request_token)
            },
            async: true,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null) {
                    if (data.Code == "OK") {
                        alert("Success");
                        return false;
                    }
                    else if (data.Code == "ERROR") {
                        alert('Error - ' + data.Message);
                        return false;
                    }
                }
            }
        });
    };

    var ajaxSyncCall = function (requestURL, typeGP, inputs, request_token) {

        $.ajax({
            url: requestURL,
            type: true,
            contentType: "application/json; charset=utf-8",
            data: inputs,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Request_Token", request_token)
            },
            async: false,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null) {
                    if (data.Code == "OK") {
                        alert("Success");
                        return false;
                    }
                    else if (data.Code == "ERROR") {
                        alert('Error - ' + data.Message);
                        return false;
                    }
                }
            }
        });
    };

    return {
        baseURL:baseURL,
        ajaxAsyncCall: ajaxAsyncCall,
        ajaxSyncCall: ajaxSyncCall
    }
})();


//Use of common Synchronous and Asynchronous methods
//GET CUSTOMERS LIST WITH SYNC CALL.
demo.ajax.ajaxSyncCall(demo.ajax.baseURL + "API/Users/GetUsersRequest", 'GET', null, function (data) {
  if (data != undefined) {
      successGetCustomers(data);
  }
}, null);

var successGetCustomers = function (data) {
  if (data) {
      console.log(data);
      //TODO: As PER YOU!
  }
};


What Is XMLHttpRequest Object in AJAX?
The XMLHttpRequest object is an API that is used to transferring data between a web browser and a web server using HTTP protocol and also provides the connection between a client and server.

The object is provided by the browsers scripting languages looks like JavaScript, JScript, and other environments.

It is also known as short name “XHR”.

The concept behind the XMLHttpRequest object was originally created by Microsoft.
The XMLHttpRequest property looks like-
1.      onreadystatechange
2.      responseText
3.      responseXML
4.      status
5.      statusText
6.      readyState : the readyState can be 0, 1, 2, 3 and 4.
a)      0-Your request is not initialized.
b)      1-Your request has been set up.
c)      2-Your request has been sent.
d)      3-Your request is in process.
e)      4-Your request is completed.
The XMLHttpRequest method looks like -
1.      abort()
2.      setRequestHeader(label, value)
3.      getAllResponseHeaders()
4.      getResponseHeader(mame)
5.      open(method, URL, async, userName, password)
6.    send(content)


The XMLHttpRequest object Syntax looks like
var xhrp = new XMLHttpRequest();


The Example looks like -
//AJAX - The Event onreadystatechange.
var loadXhr = function() {
  var xhrp = new XMLHttpRequest();
  xhrp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          document.getElementById("yourElementId").innerHTML = this.responseText;
      }
  };

  xhrp.open("GET", "ajax-info-text.txt", true);
  xhrp.send();
}


The Global error handling in the Ajax – I am trying to cover all errors to get and displays.

//jQuery global error handling Ajax

//#region NAMESPACE
var demo = demo || {};
//#endregion

//#region VARIABLES USED IN THIS JS
var obj_hdrs = [];
var obj = new Object();

//#endregion

//#region GLOBAL CONTEXT

demo.baseConst = {
    baseUrl: getBaseURL(),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    statusErrors : {
        'M400': "Server understood the request, but request content was invalid. [400]",
        'M401': "Unauthorized access. [401]",
        'M403': "Forbidden resource can not be accessed. [403]",
        'M404': "Requested page not found. [404]",
        'M500': "Internal server error. [500]",
        'M503': "Service unavailable. [503]",
        'M0': 'Not connect.\n Verify Network.',
        'MParsererror': 'Requested JSON parse failed. [Failed]',
        'MTimeout': 'Time out error. [Timeout]',
        'MAbort': 'Ajax request aborted. [Aborted]',
        'MUncaught': 'Uncaught Error.\n'
    }
}

//This method id used to get the base URL for global constant.

function getBaseURL() {
    var currentBaseURL = location.protocol + "//" + location.hostname +
        (location.port && ":" + location.port) + "/";
    return currentBaseURL;
};

//#endregion

//#region AJAX FUNCTIONS AND USER SESSION RELATED CODE

demo.ajax = (function () {

    //#region SET AJAX REQUEST HEADER

    var setHeaderRequest = function (xhr, arr_hdrs) {
        obj_hdrs = [];
        obj = new Object();

        // Common headers
        obj["RequestVerificationToken"] = tokenHeaderValue;

        obj_hdrs.push(obj);

        // Specific headers
        if (arr_hdrs !== undefined && arr_hdrs !== null && arr_hdrs !== '') {
            $.merge(obj_hdrs, arr_hdrs);
        }

        $.each(obj_hdrs, function (k, v) {
            $.each(obj_hdrs[k], function (i, val) {
                xhr.setRequestHeader(i, val);
            });
        });
    };

    //#endregion

    //#region AJAX ASYNC REQUEST

    var asyncCall = function (url, data, GETPOST, callback, arr_hdrs) {
        var global = demo.baseConst;

        $.ajax({
            url: global.baseUrl + url,
            type: GETPOST,
            contentType: global.contentType,
            data: data,
            beforeSend: function (xhr) {
                setHeaderRequest(xhr, arr_hdrs);
            },
            async: true,
            cache: false,
            success: function (data) {
                if (data !== undefined && data !== null && data !== "") {
                    if (data.Code !== undefined && data.Code !== null && data.Code !== "") {
                        if (data.Code.toLowerCase() === "ok") {
                            callback(data);                       
                        }
                        else if (data.Code.toLowerCase() === "error") {
                            demo.dialog.alertDialog('error', 'Error', 'Error', data.Message, null);
                        }
                        else {
                            demo.dialog.alertDialog('error', 'Error', 'Error', demo.constant.request.unableToProcessYourRequest, null);
                        }
                    }                   
                    else {
                        callback(data);
                    }
                }
                else if (data === null) {
                    callback(data);
                }
                else {
                    demo.dialog.alertDialog('error', 'Error', 'Error', demo.constant.request.unableToProcessYourRequest, null);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                jqXHRError(jqXHR, errorThrown);
            }
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            jqXHRError(jqXHR, errorThrown);
        });
    };

    //#endregion  

    ////#region AJAX ERROR HANDLING.
    var jqXHRError = function (jqXHR, exception) {
        var msg = '';
        var statusErrorMsg = demo.baseConst.statusErrors;

        if (jqXHR !== undefined && jqXHR !== null) {
            if (jqXHR.status === 0) {
                msg = statusErrorMsg.M0;
            }
            else if (jqXHR.status == 400) {
                msg = statusErrorMsg.M400;
            }
            else if (jqXHR.status == 401) {
                msg = statusErrorMsg.M401;
            }
            else if (jqXHR.status == 403) {
                msg = statusErrorMsg.M403;
            }
            else if (jqXHR.status == 404) {
                msg = statusErrorMsg.M404;
            }
            else if (jqXHR.status == 500) {
                msg = statusErrorMsg.M500;
            }
            else if (jqXHR.status == 503) {
                msg = statusErrorMsg.M503;
            }
            else if (exception === 'parsererror') {
                msg = statusErrorMsg.MParsererror;
            }
            else if (exception === 'timeout') {
                msg = statusErrorMsg.MTimeout;
            }
            else if (exception === 'abort') {
                msg = statusErrorMsg.MAbort;
            }
            else {
                msg = statusErrorMsg.MUncaught + jqXHR.responseText;
            }
            demo.dialog.alertDialog('error', 'Error', 'Error', msg, null);
        }
        else {
            demo.dialog.alertDialog('error', 'Error', 'Error', statusErrorMsg.MUncaught, null);
        }
    }
    ////#endregion

    return {
        asyncCall: asyncCall
    };
})();

//#endregion


Is AJAX a framework?
No! AJAX is methodology and not a language or not a framework.

The AJAX stands for “Asynchronous JavaScript and XML” and AJAX is a technique to creating interactive web applications and allows us to send and receive data asynchronously without refreshing the web page.

The XMLHttpRequest object is part of a technology called AJAX.
AJAX is very faster and easy, we can implement AJAX in a meaningful manner.

What is the difference between JavaScript and AJAX?
The JavaScript is most popular scripting languages and it developed by Netscape and used to develop the client side web applications.

JavaScript is a case sensitive because a function “str” is not equal to “Str”.

The AJAX stands for “Asynchronous JavaScript and XML” and AJAX is a technique to creating interactive web applications and allows us to send and receive data asynchronously without refreshing the web page.

What does JSON stand for?
The JSON stand for “JavaScript Object Notation” and the JSON is an open-standard file format that uses human readable text to transmit data objects consisting of attribute–value pairs and array data types.

What is the difference between JSON and AJAX?
The JSON stand for “JavaScript Object Notation” and AJAX stand for “Asynchronous JavaScript and XML”.

The both (JSON and AJAX) are completely different concepts; one is used as a storage medium for data (JSON) while the other is used to retrieve data from a HTTP or FTP web server (AJAX) which is not dependent on the format of the data to be transferred.

Is JSON is a Programming Language?
The JSON stand for “JavaScript Object Notation” and JSON is a data format and not a programming language.

Is Ajax still in use?
Yes!, Peoples still use AJAX for web applications!

The AJAX (Asynchronous JavaScript and XML) and is a technology supported by native JavaScript (ECMAScript).

It’s still the primary way that JavaScript for making a request to a server.

How can AJAX applications be debugged?
Tools for debugging -
1.      Fiddler for IE
2.      Firebug for Mozilla

How can we cancel the XMLHttpRequest in AJAX?
The Abort () method can be called to cancel the XMLHttpRequest in the AJAX.

Is AJAX code cross browser compatible?
If the browsers supports native XMLHttpRequest JavaScript object, then this can be used otherwise no.

What are the protocols used by AJAX?
1.      HTTP’s GET or POST
2.      XMLHttpRequest for placing a request with the web server
3.      Uses JSON to communicate between the client and server
4.      UED or URL encoded data

What are all the different data types that JSON supports?
The JSON supports following data types -
1.      String
2.      Number
3.      Boolean
4.      Array
5.      Object
6.      Null

I hope you are enjoying with this post! Please share with you friends. Thank you so much!
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - https://code-sample.com and https://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions