Friday, 17 July 2015

Jquery Interview Questions and Answers for experienced

jquery interview questions and answers for experienced
Question: What is jQuery?
jQuery is a fast, small and feature-rich JavaScript library.
jQuery makes things like HTML document traversal and manipulation, animationevent handling and Ajax much simpler with an easy-to-use API.
It works across a multitude of browsers.


Question: What is Ajax?
Ajax( Short form of Asynchronous JavaScript and XML) is a Web development techniques used on the client-side to create Synchronous OR asynchronous Web applications. It is used to get the data from server without refresh the page.


Question: What is Iframe?
Iframe is an HTML document embedded inside another HTML document on a website. We can embed one OR many iframe in one website.


Question: What is element in HTML?
An HTML element is an individual component of an HTML document or web page.
For example, p,div,span etc know as element.
when these surrounded by angle brackets know as HTML Tags.


Question: What is event in jQuery? Doing any thing, known as event.
For Example, Click event, mouseover event, blur event, double click event etc.


Question: What is jQuery event?
A jQuery object is array-like which means that it contains zero or more indexes.


Question: How to parse a JSON String?
var obj = jQuery.parseJSON( '{ "name": "John" }' );
console.log( obj.name);



Question: How to communicate between iframe and the parent site?
With same domain and same port/protocol
you can use window.opener to change in parent window from child window.
you can use document.getElemetById('#iframeId') to change in child window from parent window.
With different domain OR different port/protocol
You have to use cross-document messaging.

Question: How can I select an element by name or class or id with jQuery?
Select by name
console.log($('div[name=divname]'));

Select by class name
console.log($('div.className'));

Select by classId
console.log($('div#classId'));



Question: How to show the preview an image before it is uploaded to server?
To show the preview you need to use "FileReader" javascript function.
See Demo:http://jsfiddle.net/LvsYc/


Question: How to get html tags from string?
var re = /(<([^>]+)>)/ig; 
    var str = '

Hello!

'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } } console.log(re);



Question: What is use $.each? Give examples?
It is similar to foreach in jQuery.
you can use $.each for normal array OR list of elements. For Example:
$('a.myclass').each(function(index, value){
      console.log($(this).attr('href'));
});

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value); 
});



Question: What's the difference between jquery.js and jquery.min.js?
Both are same.
only difference jquery.min.js is minified file which have no space, tab.

Question: How to add Email Validation in jQuery?
function IsValidEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}
console.log(IsValidEmail('myvalidemail@domain.com'));
console.log(IsValidEmail('myInvalidemail@'));
console.log(IsValidEmail('myInvalidemail#domain.com'));



Question: How to get nth jQuery element?
use eq function.
console.log($("div.myclass:eq(2)")); 



Question: How to remove a row from table?
$('tr#myTableRowId').remove();
OR
$('tr.myTableRowClass').remove();


Question:How to bind shortcut-keys with jQuery?
To bind Ctrl+f to a functionName.
$(document).bind('keydown', 'ctrl+f', functionName);

You can check also: http://github.com/jeresig/jquery.hotkeys


Question: How to convert array to JSON?
You can use stringify.
var yourArray = Array('1','2','3','4');
var myJsonString = JSON.stringify(yourArray);



Question: How to check if a div exists with jquery?
if($("div#idName" + name).length > 0) {
  /** It is exist **/
}



Question: How to call a function after 3 seconds?
setTimeout(
  function(){
/** Do here **/

/** Do here **/    
  }, 3000);
}



Question: How to prevent caching in Ajax?
After loading of jQuery, add the below code at the top of all ajax call.
$.ajaxSetup({ cache: false });

Tuesday, 14 July 2015

Ajax technical interview questions and answers for experienced


Ajax technical interview questions and answers for experienced


Question: How can AJAX response set a cookie?
Here are two solutions.
  1. After getting response, Make another ajax call with request where you can set the cookie.
  2. Before sending the ajax response, make the cookie in Server.
Use setcookie function, to set the cookie, like below
$cookieValue='This is cookie value';
setcookie('name', $cookieValue, time() + 3600); 



Question: How to send data in Ajax call?
$.ajax({ 
        url: '/my/site/url',
         data: { name: "Arun", location: "Chandigarh" },
         type: 'post',
         success: function(result) {
                      console.log(result);
          }
});



Question: How to submit entire form data with Ajax?
var formData = $('form#formId').serialize();
$.ajax({ 
        url: '/my/site',
         data: formData,
         type: 'post',
         success: function(result) {
                      console.log(result);
          }
});


Question: What are different readystate stages in Ajax Call?
In Ajax call, ready state have 5 values and are following:
  1. 0- The request is not initialized.
  2. 1- The request has been set up.
  3. 2- The request has been sent.
  4. 3- The request is in process.
  5. 4- The request is complete.



Question:Give a simple example of JSONP with Ajax?
$.getJSON("http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=?", function(result){
   //Now result have response of ajax call
   console.log(result);
});



Question: How to URLencode a string Before sending in Ajax?
use encodeURIComponent to encode a string, For Example:
 $.ajax({
        url: '/ajax/url',
        dataType: "json",
        data: name=encodeURIComponent('Test'),
        success: function(response) {
            if(response.success == 1){
                offWords = response.data;
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
        }
    });



Question: Do AJAX requests retain PHP Session info, when calling muliple times?
Yes, PHP retain the session info over multiple ajax call.
Duration of available of php session depend of SESSION configuration.


Question: How to update the image source, if original image fails to load?
Use the onError attribute to update the image path, when failed to load.
<img alt="Image not found" onerror="this.src=&#39;show_img_when_original_failed.gif&#39;;" src="image.gif" />



Question: What is Comet in web application?
Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it


Question: How to add header in AJAX Request?
 $.ajax({
    type:"POST",
    beforeSend: function (request)
    {
        request.setRequestHeader("Header-Name", "Header Value");
    },
    url: "/ajax/url/",
    data: "name=web",
    processData: false,
    success: function(msg) {
        //Success
    }
    });



Question: How to do synchronous AJAX requests?
set async=false in ajax call.
function getRemote() {
    return $.ajax({
        type: "GET",
        url: '/ajax/url',
        async: false
    }).responseText;
}



Question: How to set all ajax call synchronous?
Set the following in after include of jQuery
$.ajaxSetup({async:false});



Question: How to send a ajax call with https when you are http page(Suppose same domain)?
Add following in header of Ajax Call.
Access-Control-Allow-Origin: http://www.domain.com



Question: How to get the error response text in Ajax?
$.ajax({
    type:"POST",
    url: "url",
    data: "name=web",    
    error: function(xhr, status, error) {
      var err = eval("(" + xhr.responseText + ")");
      console.log(err.Message);
    }
    success: function(msg) {
        //Success
    }
    });



Question: Getting all selected checkbox in an array?
var selectedIds = new array();
$("input:checkbox[name=type]:checked").each(function(){
    selectedIds.push($(this).val());
});
console.log(selectedIds);