Friday, 20 November 2015

Top 10 Ajax interview Questions and Answers

Top 10 Ajax interview Questions and Answers



Question 1: Give basic example of JSONP with Ajax?
Full Form of JSONP is JSON with padding.
JSONP is a simply way to overcome the XMLHttpRequest same domain policy. (As we know, we can't send Ajax request to a different domain.)
But with use of JSONP we can do the same.

$.getJSON("http://example.com/file.json?callback=?", function(result){
   console.log(result); //Here response will comes   
});



Question 2: How to add header in Ajax call?
Way 1: Add Header in Ajax call
$.ajax({
    url: '/aja/ajax-call',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    }
  });

Way 2: Add Header Before send the Ajax call
$.ajax({
    url: '/aja/ajax-call',
    beforeSend: function (request){
       request.setRequestHeader("Authority", authorizationToken);
    },
    method: 'POST',
    dataType: 'json',
    data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    }
  });




Question 3: URL Encode a string before sending in Ajax call?
$.ajax({
    url: '/aja/ajax-call', 
    method: 'POST',
    dataType: 'json',
   data: 'name=test&age=20&gender=m&url='+encodeURIComponent('http://web-technology-experts-notes.in'),
    success: function(data){
      console.log(data);
    }
  });



Question: Do AJAX requests retain PHP Session info?
Yes,


Question 4: What should i do when i didn't get result in Ajax Call? use error:, I ajax code. For Example:
$.ajax({
    url: '/aja/ajax-call', 
    dataType: 'json',
   data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    },
    error: function ( jqXHR, textStatus, errorThrown ) {
        console.log(jqXHR+'-'+textStatus+'-'+errorThrown);
      },
  });



Question 5: How to send ajax request synchronously? set async as false, for Example
$.ajax({
    url: '/aja/ajax-call', 
    dataType: 'json',
   data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    },
    async:false ,
  });



Question 6: Can we send post data with JSONP?
No, we can get only results with JSONP


Question 7: How to get the jQuery $.ajax error response text?
Add following node, in $.ajax,
error: function(xhr, status, error) {
  var err = xhr.responseText;
}



Question 8: How to pass entire form in Ajax call?
First serialize the form data and pass in ajax call. For Example.
$.ajax({
    url: '/aja/ajax-call', 
    dataType: 'json',
   data: $('form#formId').serialize(), /* Must be serialized **/
    success: function(data){
      console.log(data);
    },
    error: function ( jqXHR, textStatus, errorThrown ) {
        console.log(jqXHR+'-'+textStatus+'-'+errorThrown);
      },
  });



Question 9: What are different readyStates in XHLHttpRequest?
State     Description
0- The request is not initialized
1- The request has been set up
2- The request has been sent
3- The request is in process
4- The request is complete


Question 10: How we can upload the image with Ajax?
use uploadify plugin.
http://www.uploadify.com/demos


Thursday, 19 November 2015

Top 10 jQuery interview Questions and Answers

Top 10 jQuery interview Questions and Answers


Question: How to replace the text of div using class?
Suppose HTML
<div class="myDivClass">
Update this text</div>
jQuery code 
$('.myDivClass').text('Updated'); 



Question: How to replace the text of div using "div id"?
Suppose HTML
<div id="myDivId">
Update this text</div>
jQuery code 
$('#myDivId').text('Updated'); 



Question: How to replace the html of div using class?
Suppose HTML
<div class="myDivClass">
Update this html</div>
jQuery code 
$('.myDivClass').html('Updated'); 



Question: How to replace the text of div using "div id"?
Suppose HTML
<div id="myDivId">
Update this text</div>
jQuery code 
$('#myDivId').html('Updated'); 



Question: How to Check if checkbox is checked?
Suppose HTML is
<input name="lang[]" type="checkbox" value="English" />
<input name="lang[]" type="checkbox" value="Hindi" />
<input name="lang[]" type="checkbox" value="Urdu" />

JQuery code
var totalCheckboxSelected = $('input[name="lang[]"]:checked').length;
if(totalCheckboxSelected){
    console.log(totalCheckboxSelected+' check box checked');
}else{
    console.log('NO checkbox is selected');
}



Question: How can you check for a #hash in a URL?
if(window.location.hash) {
    var hashValue = window.location.hash.substring(1);
    console.log(hashValue);
} else {
  console.log('Hash not found');
} 



Question: How get to know which mouse button is pressed?
$('#divId').mousedown(function(event) {
    switch (event.which) {
        case 1:
            console.log('Left button pressed.');
            break;
        case 2:
            console.log('Middle button pressed.');
            break;
        case 3:
            console.log('Right button pressed.');
            break;
        default:
            console.log('Exception Case!');
    }
});



Question: How to add update the color of div with jQuery?
$('div#divId').css("background-color", "red");



Question: How to remove class from div?
$("div#divId").removeClass('className'); 



Question: How do I get the value of a textbox using jQuery?
Html

<input id="websiteId" name="website" type="text" value="Web Technology Experts Notes" /> jQuery:
$("#websiteId").val();



Question: How to submit form with post method with Ajax?
HTML Form
<form action="/ajax/form-url" id="ajaxform" method="POST" name="ajaxform">
First Name: <input name="fname" type="text" value="" /> <br />
Last Name: <input name="lname" type="text" value="" /> <br />
<input name="submit" type="submit" value="Submit the Form" /> </form>

jQuery Code
$( document ).ready(function() {
    $("#ajaxformSubmit").submit(function(e)
    {
        var postData = $(this).serializeArray();
        var formURL = '/ajax/form-url'
        $.ajax(
        {
            url : formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus) 
            {            console.log(data);
            }
        });
        e.preventDefault(); //STOP default action
    });
});



Question: How to escape the text?
var someHtmlString = "";
var escaped = $("
").text(someHtmlString).html(); console.log(escaped); //<script>aalert('hi!');</script>