HI WELCOME TO KANSIRIS
Showing posts with label Interview q&a. Show all posts
Showing posts with label Interview q&a. Show all posts

AJAX Interview Questions and Answers

Leave a Comment

 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:valuename: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 (data1data2data3data4) {
      //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(mySuccessmyFailure);

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 (requestURLtypeGPinputsrequest_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 (requestURLtypeGPinputsrequest_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'nullfunction (data) {
    if (data != undefined) {
        successGetCustomers(data);
    }
}, null);

//GET CUSTOMERS LIST WITH ASYNC CALL.
demo.ajax.ajaxAsyncCall(demo.ajax.baseURL + "API/Users/GetUsersRequest"'GET'nullfunction (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 (asyncfalse) 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 (requestURLtypeGPinputsrequest_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 (requestURLtypeGPinputsrequest_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'nullfunction (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 (requestURLtypeGPinputsrequest_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 (requestURLtypeGPinputsrequest_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'nullfunction (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 (xhrarr_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_hdrsarr_hdrs);
        }

        $.each(obj_hdrsfunction (kv) {
            $.each(obj_hdrs[k], function (ival) {
                xhr.setRequestHeader(ival);
            });
        });
    };

    //#endregion

    //#region AJAX ASYNC REQUEST

    var asyncCall = function (urldataGETPOSTcallbackarr_hdrs) {
        var global = demo.baseConst;

        $.ajax({
            url: global.baseUrl + url,
            type: GETPOST,
            contentType: global.contentType,
            data: data,
            beforeSend: function (xhr) {
                setHeaderRequest(xhrarr_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.Messagenull);
                        }
                        else {
                            demo.dialog.alertDialog('error''Error''Error'demo.constant.request.unableToProcessYourRequestnull);
                        }
                    }                   
                    else {
                        callback(data);
                    }
                }
                else if (data === null) {
                    callback(data);
                }
                else {
                    demo.dialog.alertDialog('error''Error''Error'demo.constant.request.unableToProcessYourRequestnull);
                }
            },
            error: function (jqXHRtextStatuserrorThrown) {
                jqXHRError(jqXHRerrorThrown);
            }
        })
        .fail(function (jqXHRtextStatuserrorThrown) {
            jqXHRError(jqXHRerrorThrown);
        });
    };

    //#endregion  

    ////#region AJAX ERROR HANDLING.
    var jqXHRError = function (jqXHRexception) {
        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;