Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Friday, 1 April 2016

Ajax Interview Questions and Answers for Fresher

Ajax Interview Questions and Answers for Fresher

Question: What are the advantages of AJAX?
  1. Quick Response.
  2. Quick Response without loading page.
  3. Save the Bandwidth
  4. Client Server Interaction what user letting know (User will not get disturb)



Question: What are the dis Advantages of AJAX?
  1. Dependency on JavaScript.
  2. An simple js error, Ajax will not called.
  3. Security issues Might comes, if not implemented securely.
  4. Difficult in Debugging for beginner
  5. Sometimes browser compatibility issues comes.



Question: What are top website, who uses Ajax?
  1. Youtube
  2. Google
  3. Bing
  4. Gmail
  5. Twitter
  6. Linkdin



Question: What are security issues in AJAX?
  1. Ajax is visible in browser console
  2. Request, Response, header and cookie are visiable in browser console.
  3. Every time called ajax is purely visiable in Ajax
  4. An Ajax request can be called by hackers OR unauthorized, It can damage the website if there are not properly security checks
  5. Attackers can try the ajax call with different request parameter.



Question: What are the technologies used by AJAX?
  1. Javascript
  2. XMLHttpRequest
  3. XML/JSON/HTML
  4. DOM
  5. You can also use third party libaraies like jQuery, mootools etc



Question: What are common AJAX Framework?
  1. jQuery
  2. MooTools
  3. Prototype
  4. YUI
  5. Dojo Toolkit
  6. Google Web Toolkit (GWT)



Question:What are Ajax applications?
The web applicable which use the more ajax calls are ajax application.


Question: What are different stage of XMLHttpRequest?
  1. 0: request not initialized
  2. 1: server connection established
  3. 2: request received
  4. 3: processing request
  5. 4: request finished and response is ready



Question: In Ajax call, which method is more secure GET/Post?
POST is more secure as compare to Get Method.


Question: Can anyone send ajax request with POST Method ?
Yes, can send using CURL.


Question: What is the difference between JavaScript and AJAX? JavaScript an object-oriented computer programming language used in web browsers.
Ajax is set of web development techniques using JavaScript to send/receive the data from server without loading page.


Question: What is Asynchronous in Ajax?
We can set the Asynchronous value as true OR false.
Async=true

Ajax request execute independently, Its response can come earlier than other request which is execute later .
Async=false
Ajax request does not execute independently, Its response can comes when earlier request finished.


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



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);
});



Thursday, 24 March 2016

How to Stop ajax requests in jQuery?

How to Stop ajax requests in jQuery

HTML Code



<!--- HTML Part --->
<form id="formId" method="POST" onsubmit="return saveData()">
<input name="formsubmit" type="hidden" value="1" />
    First Name:  <input name="first_name" type="text" />
    <br />
Last Name:  <input name="last_name" type="text" />
    <br />
Email: &nbsp;   &nbsp;  &nbsp;   &nbsp;<input name="email" type="text" /><br />
<input type="submit" value="Click to Submit" />
</form>
<!--- HTML Part --->



jQuery/JavaScript Code



<!--- Javascript Part --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
var request=0;
    function saveData() {
        if(request!=0){
   request.abort();
  }
         request=$.ajax({
            url: "ajax.php",
            method:"post",
            data: $('form#formId').serialize()+'&phone=789797522&city_id=1',
            cache: false,
            success: function(msg) {
                console.log(msg);
    request =0;
            }
        });
  
        return false;
    }

</script>
<!--- Javascript Part --->



PHP Code



if(!empty($_POST)){
    echo "<pre>";
    print_r($_POST);
 echo "</pre>
";
    /** You can write your code here **/    
    

/** You can write your code here **/        
    die;
}



PHP Output Code


Array
(
    [formsubmit] => 1
    [first_name] => Raj
    [last_name] => sinha
    [email] => [email protected]
    [phone] => 789797522
    [city_id] => 1
)





Wednesday, 23 March 2016

How to send ajax request in PHP?

How to send ajax request in PHP?

HTML Code



<!--- HTML Part --->
<form id="formId" method="POST" onsubmit="return saveData()">
<input name="formsubmit" type="hidden" value="1" />
    First Name:  <input name="first_name" type="text" />
    <br />
Last Name:  <input name="last_name" type="text" />
    <br />
Email: &nbsp;   &nbsp;  &nbsp;   &nbsp;<input name="email" type="text" /><br />
<input type="submit" value="Click to Submit" />
</form>
<!--- HTML Part --->



jQuery Code



<!--- Javascript Part --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
    function saveData() {
        
        $.ajax({
            url: "ajaxfile.php",
            method:"post",
            data: $('form#formId').serialize()+'&phone=789797522&city_id=1',
            cache: false,
            success: function(msg) {
                console.log(msg);
            }
        });
        return false;
    }

</script>
<!--- Javascript Part --->



PHP Code



if(!empty($_POST)){
    echo "<pre>";
    print_r($_POST);
 echo "</pre>";
    /** You can write your code here **/    
    

/** You can write your code here **/        
    die;
}



PHP Output Code


Array
(
    [formsubmit] => 1
    [first_name] => Raj
    [last_name] => sinha
    [email] => [email protected]
    [phone] => 789797522
    [city_id] => 1
)





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);


Monday, 13 April 2015

Ajax interview questions and answers for 1 year experience

Ajax interview questions and answers for 1 year experience


Question: How to set header in Ajax where they are using Get Method?
After jQuery 1.4, You can set the header data in $.ajax method.
You can set the header data in "headers" node, by default header value is empty {}.
See Example:
$.ajax({
    url: "/ajax/myfile.php",
     data: 'pro=web+technology+experts+notes',
     type: "GET",
     headers: {"X-Test-Header-Key": "header-value"}
});



Question: How to pass multiple parameter in Ajax call?
When you are using $.ajax method, we can pass multiple parameters in ajax call.
See Example:
$.ajax({
    url: "/ajax/myfile.php",
     data: JSON.stringify({ field1: 'value1', field2: 'value2',field3: 'value3' }),
     type: "GET",
     headers: {"X-Test-Header-Key": "header-value"},
    error: function(xhr, status, error) {
        // when ajax call (get OR POST), failed, this node will be called.
      //console.log(xhr);    
  
    }
});



Question: How to do error handling in Ajax Call?
Whenever ajax call failed due to any reason, you can get the error response in error node of ajax call.
See Example:
$.ajax({
    url: "/ajax/myfile.php",
     data: 'pro=web+technology+experts+notes',
     type: "GET",
     headers: {"X-Test-Header-Key": "header-value"},
    error: function(xhr, status, error) {
        // when ajax call (get OR POST), failed, this node will be called.
      //console.log(xhr);    
  
    }
});



Question: How to call multiple Ajax request in single click with callback function?
You can use $.when method of jQuery.
See Example:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
  .then( myFunc, myFailure );



Question: How to Pass entire form as data in jQuery Ajax function?
To get the entire form data use following code:
var formData = $('form').serialize();

Now formData, have all the html form data.
You can pass this variable in ajax call.
See Example:
var formData = $('form').serialize();
$.ajax({
    url: "/ajax/myfile.php",
     data: formData,
     type: "GET",
     headers: {"X-Test-Header-Key": "header-value"},
    error: function(xhr, status, error) {
        // when ajax call (get OR POST), failed, this node will be called.
      //console.log(xhr);    
  
    }
});



Question: How is GMail Chat able to make AJAX requests without client interaction?
When we are using gmail inbox, we notice that emails are automatic refresh after some time. and also there are no ajax call.
This is possible with technique like comet.
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.


Question: What are JSON security best practices?
1. Don't use uses cookies for authentication.
2. Don't pass sensitive information in JSON Response.
3. You can use POST Method.
4. Add http referer check in server side, means server return response, only if request from same domain.


Question: How to upload images with ajax?
Today's lot of js framework plugins are available for uploading images, text file, videos with ajax, means upload files without page refreshing.
See Below Example:
http://js1.hotblocks.nl/tests/ajax/file-drag-drop.html
http://www.uploadify.com/demos/




Question: How to load data on scroll down?
When user scroll data the page, scipt will compare the height of whole page vs scrolled page, If there is now less space at bottom. Ajax call will sent to server with page number and append that result into current page.
We have create same script for you.
See Example Below
var page=0;
$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        page++;

        $.ajax({
            url: "/ajax/load-data.php?page="+page,//this must return the html instead of json             
             type: "GET",
             success:function(data){
                 //Here data will be all the new html, you need to append this to existing page like below
                    $('#container').append(data);
            }
            error: function(xhr, status, error) {
                // when ajax call (get OR POST), failed, this node will be called.
              //console.log(xhr);    

            }
        });



    }
});





Question: How to parse json data with jquery / javascript in ajax call and in Normal text? In ajax call, if response is coming in JSON format, then we must set datatype as JSON in ajax. See Example below:
$.ajax({
    url: "/ajax/load-data.php",
     type: "GET",
     dataType: 'json',
     success:function(data){         
        //Now you can handle JSON Response
    }
    error: function(xhr, status, error) {
    //Error handling here 

    }
});
If there are data in normal text and we want to parse the text with use of parseJSON method. See Example:
$.parseJSON(planTextData);



Question: How to check, if string is JSON OR NOT?
We can use JSON.parse method to check JSON is valid OR NOT.
var stringData='{json:data}';
try
{
   var json = JSON.parse(stringData);
}
catch(e)
{
   //console.log('invalid json');
}






Sunday, 5 April 2015

Ajax Interview Questions and Answers for 3 Year Experienced

Ajax Interview Questions and Answers for 3 Year Experienced



Question: How to send ajax request to another domain using JSONP?
JSONP is simple way to overcome XMLHttpRequest same domain policy. With use of JSONP you can send the request to another domain. JSONP is "JSON with Padding", In JSONP we include another domain URL with a parameter i.e callback.
callback's value have a function name which must be present in your webpage.
See Example:
<script>
function myCalllbackFunction(data){
  console.log(data);
} 
</script>

 <script src="http://twitter.com/status/user_timeline/padraicb.json?count=10&amp;callback=myCalllbackFunction" type="text/javascript"></script>



Question: CanAJAX requests retain PHP login info?
Yes, I can be.


Question: How can I detect that the Internet connection?
Very simple.
Make a ajax call to reliable server which always return data. To check the Internet connection, request the data to the server. If ajax call return data, internet connection is working else not. But make sure, ajax response must not come from browser cache. For this set the cache:false in ajax call.


Question: How to send Query string(If query string is full URL) in Ajax call?
use encodeURIComponent() before sending query string.
var url=encodeURIComponent(url);


Question: How to send ajax call with https on http page (Suppose, both https and http are same domain)?
If both protocall have same domain, then you can send all ajax request with https on both (https and https page).
Add Following in ajax Header
Access-Control-Allow-Origin: https://www.youwebsitedomain.com



Question: How to get response header of AJax Call?
$.ajax({
    url: '/ajax',
    success:function(data, textStatus, request){
      console.log(request.getResponseHeader('some_header'));
    
    }
});   


Question: Can I handle the redirection of xmlhttprequest in Ajax Call?
No,


Question: How can I get the values of all sected checkbox?
$("input:checkbox[name=type]:checked").each(function()
{
//JS array of selected checkbox
    
});



Question: How to pass entire form data in Ajax?
   function onSubmitFunction(){
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: $('#mytestForm').serialize(),
        success: function(msg){
            //console.log(msg); 
        }
    });
    return false;
}


Question: How to get the error messages in jQuery Ajax?
   function onSubmitFunction(){
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: $('#mytestForm').serialize(),
        success: function(msg){
            //console.log(msg); 
        },
       error: function (request, error) {
              console.log(arguments);              
          }
    });
    return false;
} 



Friday, 3 April 2015

Ajax Interview Questions and Answer for 1 Year Experienced




Ajax Interview Questions and Answer for Experienced

Question: How to Abort ajax requests using jQuery?
Use abort() function to abort a ajax request.
See Example Below:
var ajaxRequest = $.ajax({
    type: "POST",
    url: "/ajax",
    data: "name1=value1&name2=value2",
    success: function(msg){
       //here success comes
    }
});

//Abort the ajax request
ajaxRequest.abort()

When you abort the ajax call, you can see ajax request as aborted in browser console.


Question: How to redirect a page after success of Ajax call?
You can use window.location.href, to redirect.
See Example Below:
$.ajax({
    type: "POST",
    url: "/ajax",
    data: "name1=value1&name2=value2",
    success: function(msg){
        if(msg.success){
            window.location.href='/newpage.php';
        }
       //here success comes
    }
});



Question: How do I test an empty object?
You can use jQuery isEmptyObject().
See Example Below:
var myArray=new Array();
console.log($.isEmptyObject(myArray));//return true

var myArray=new Array('This is message');
console.log($.isEmptyObject(myArray));//return false


Question: How to submit a form in Ajax?
We can use jQuery ajax function to submit a Form.
See Example Below:
Following is Javascript function
   function onSubmitFunction(){
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: $('#mytestForm').serialize(),
        success: function(msg){
            if(msg.success){
               //here success comes
            }

        }
    });
    return false;
}

Following is HTML Code
<form id="mytestForm" onsubmit="return onSubmitFunction()">
Name: <input name="name" type="text" /><input name="submit" type="submit" value="Submit" />
</form>



Question: How to get the value of textarea?
You can use val function of jQuery to get the text of textarea.
See Below:
console.log($('textarea#idOfTextArea').val());


Question: How to send AJAX call without jQuery?
For sending ajax call in IE7+, Firefox, Chrome, Opera, Safari
XMLHttpRequest
For sending ajax call in IE
use ActiveXObject

See Example Below:
function callAjax(url,method) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
            // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {

                //console.log(xmlhttp.responseText);
            }
        }
    }

    xmlhttp.open(method, url, true);
    xmlhttp.send();
}
callAjax('/ajax?data=1','GET')


Question: How to make all ajax call cache Free?
$.ajaxSetup ({
    // Disable the caching of AJAX responses for all Ajax
    cache: false
});


Question: How to download file?
very simple
window.location="/folder/file.pdf"


Question: How can I add a custom HTTP header in Ajax?
Just Use the header parameter to set the custom header
$.ajax({
    url: '/ajax',
    headers: { 'x-my-custom-header': 'I am good' }
});



Monday, 9 March 2015

Ajax Interview questions and answers for experienced


Ajax interview questions and answers for experienced
Ajax is a client-side script that communicates with server without refresh the complete page. You can also say "the method of exchanging data with a server, and updating parts of a web page without reloading the entire page". Ajax is used in all web-technology like PHP, ASP, Java and Mobile Technology etc.



Question: What is Ajax?
AJAX (Asynchronous JavaScript and XML) is a client-side script which is used to get the data from Server.


Question: Why Ajax is used?
Ajax is used to get the data from server without refreshing the current page.


Question: When we can use Ajax? Give Few Examples?
Ajax can be used to get the data from Server when you don't want to refresh the page. See Below Scenario:
  • In Registration Page, check the username is available OR NOT.
  • In Registration page, check email address is already taken OR NOT.
  • In Product Listing page, when user click on "Next" under pagination, you won't want to show the next page data without refreshing the page.


Question: What files need to install to use Ajax in Website?
Initially, no files required to use the ajax in your website.
But to manage your ajax call in better way, you can use JS library which world used to use.


Question: What js library are available to use the Ajax?
Following are few JS library which are used for Ajax
  • JQuery
  • MooTools
  • Prototype
  • YUI Library
  • Backbone js


Question: What Browsers support Ajax?
Today, All the Browser support ajax. Following are minium version of browser which support Ajax.
  • Internet Explorer 5.0 and up,
  • Opera 7.6 and up,
  • Netscape 7.1 and up,
  • Firefox 1.0 and up,
  • Safari 1.2 and up,



Question: How Ajax Works?
How Ajax Works











Question: What is XMLHttpRequest?
XMLHttpRequest is an API available to web browser scripting languages (i.e. JavaScript).
It is used to send HTTP/HTTPS requests to a web server and load the server's response into the script.


Question: How we can send data to server using Ajax?
We can use GET OR POST Method to send data.


Question: What is Asynchronous in Ajax?
We can set the Asynchronous value as true OR false.
Async=true
Ajax request execute independently, Its response can come earlier than other request which is execute later .
Async=true
Ajax request does not execute independently, Its response can comes when earlier request finished.


Question: What do the different readystates in XMLHttpRequest?
Following are different stats(0-4) of ready state in XMLHttpRequest
0 Ajax Request not initialized
1 Ajax Request's server connection established
2 Ajax Request received
3 Ajax Request processing
4 request finished and response is ready.


Question: Can I send Ajax Request to another domain?
No, you can't do this.


Question: What are advantage of AJax?
  • Its faster as it load only required content.
  • More user friendly.
  • One page application possible due to Ajax.
  • Reduce the loading of page.


Question: What are disadvantage of Ajax?
It does not crawl to search Engine.


Question: Define JSON?
JSON is JavaScript Object Notation.


Question: What type of response we can get in Ajax Response?
  • text data
  • html data
  • JSON data
  • XML data



Question: Describe how to handle concurrent AJAX requests?
JavaScipt Closures can be used for handling concurrent requests.



Question: How do you know that an AJAX request has completed?
If readyState's value is 4 means its completed.




Sunday, 15 February 2015

Synchronous XMLHttpRequest on the main thread is deprecated

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

If you are getting above issue, It means in Ajax call ( May be using xmlHttpRequest, jQuery.js OR prototype.js etc), Somewhere you have set following:
async: false

Never use "async: false", Because it has been deprecated.

async must be true, whether you are using core ajax, jQuery ajax OR prototype ajax etc.



Friday, 14 March 2014

Improve Ajax Performance

Improve Ajax Performance

Following are few steps to Improve Ajax Performance
  1. First try to Reduce the Number of Ajax Call
  2. If same call send again, abort the previous call
  3. If ajax call is executing, and user go for another link, then cancel the previous one.
  4. Use GET Method, As its Fast but less secure
  5. Reduce the Amount of data transmitted
    a. Only Required parameter in Ajax Request
    b. Only Required Response in Ajax Request
  6. Optimize your Server  


Saturday, 22 February 2014

Firebase Chat with Facebook and Twitter Integration

FireBase Chat
1). Its Free
2). You can integrate with Facebook/Twitter/Github etc
3) You can manage Chat (Can View/Update/Delete)
4) You can export chat in Json Form
5) API Available

Demo: http://firebase.github.io/firechat/

Tutorial: http://firebase.github.io/firechat/docs/




How to setup firebase chat
1) Register to https://www.firebase.com/
2) Login to your firebase account similar to https://blistering-fire-9888.firebaseio.com/
3) Go to Dashboard=>Simple Account
a) Add list of domains where your chat will be run, (for example localhost, www.example.com)
b) Set "Authentication Providers"
Here you can enable provider (Facebook|Twitter etc)
Enable the checkbox and put the required credentials

For facebook
i) Create a app
ii) In Site URL put "https://auth.firebase.com/auth/facebook/callback"
iii) In "Site and Review", Enable the app for public
iv) Copy your "App ID" and "App Secret" from "Settings" and paste in "firebase.com=>Simple Login=>Facebook"

For Twitter
i) Create a App in twitter.com
URL: https://apps.twitter.com/
ii) In Callback URL set " https://auth.firebase.com/auth/twitter/callback"
iii) Copy "API key" and "API secret" from twitter apps and paste in "firebase.com=>Simple Login=>Twitter" (Twitter Consumer Key,Twitter Consumer Secret)

4) Open Below URL's
http://firebase.github.io/firebase-simple-login/
a) Click on "Launch demo" of Facebook Link
b) Click on "Launch demo" of Twitter Link



Sunday, 30 June 2013

jQuery Function with Examples

jQuery Function with Examples


jQuery Functions with example which used mostly in web development

To use following functions you have to include jQuery file from jquery.com

.add() : Add elements to the set of matched elements. Example Add div to all p elements
$("p").add("div")


.addBack() : Add the previous set of elements on the stack to the current set, optionally filtered by a selector. Example Add class "background" to all the "div" having class "after"
$("div.after").find("p").addBack().addClass("background");


.after(): Insert content, specified by the parameter, after each element in the set of matched elements. Example Add the content "Test Message" just after "div" having "after" class
$('div.after').after('Test Message');


.ajaxComplete(): Register a handler to be called when Ajax requests complete. Example ajaxComplete will be called automatically just after finishing the ajax
$(document).ajaxComplete(function(event,request, settings) {
alert( "Request Complete." );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxError(): Register a handler to be called when Ajax requests complete with an error. Example ajaxError will be called automatically just after finishing the ajax with error
$(document).ajaxError(function(event, jqxhr, settings, exception) {
alert( "Request Complete with Error." );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxSend(): Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time. Example ajaxSend will be called automatically when ajax is about to be sent.
$(document).ajaxSend(function(event, jqxhr, settings) {
alert( "Ajax Request just send" );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxStart(): Register a handler to be called when the first Ajax request begins. This is an Ajax Event. Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with the .ajaxStart() method are executed at this time. Example ajaxStart will be called automatically when ajax request start
$(document).ajaxStart(function() {
alert( "Ajax Request just send" );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxStop(): Description: Register a handler to be called when all Ajax requests have completed. Example Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event. Any and all handlers that have been registered with the .ajaxStop() method are executed at this time. The ajaxStop event is also triggered if the last outstanding Ajax request is cancelled by returning false within the beforeSend callback function.
$( ".log" ).ajaxStop(function() {
$(this).text( "Triggered ajaxStop handler." );
});


.ajaxSuccess(): Attach a function to be executed whenever an Ajax request completes successfully. Example Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
$(document).ajaxSuccess(function() {
$( ".log" ).text( "Triggered ajaxSuccess handler." );
});


.andSelf():Add the previous set of elements on the stack to the current set. Example This function has been deprecated and is now an alias for .addBack(), which should be used with jQuery 1.8 and later. As described in the discussion for .end(), jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .andSelf() can help. animate(): Perform a custom animation of a set of CSS properties. The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a plain object of CSS properties. This object is similar to the one that can be sent to the .css() method, except that the range of properties is more restrictive. Example
$('a.clickMe').click(function() {
$('#effect').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 5000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function() {
$(this).after('
Animation complete.');
} }); });


.contents(): Get the children of each element in the set of matched elements, including text and comment nodes. Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search throughthe immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents() and .children() methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.


Form Submit By Ajax - Simple Example
    function submitme(){
        var data= $('#form').serialize();
        var url ="/ajax/submiturl";

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            success: function(data){
                alert(data);
            },
            dataType: 'json'
        });

    }


Monday, 27 May 2013

Ajax Methods in JQuery

Ajax Methods in JQuery

jQuery Load Method
load(): Load a piece of html into a container DOM.
$('#result').load('ajax/test.html');

jQuery GET Method
$.get(): Use this if you want to make a GET call and play extensively with the response.
$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

jQuery POST Method
$.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

jQuery AJAX Method
$.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});




jQuery getJSON Method
Return the Response in JSON Format
$.getJSON("/ajax/json_response", function(result){
    console.log(result)
        
    });



Sunday, 15 July 2012

jQuery Fancybox

jQuery Fancybox



Is your need?
  • Image in Popup
  • Image Gallery in Popup
  • Inline data in popup 
  • Ajax data in Popup
  • Call callback function with popup
  • Google Map in Popup 

If above of anyone is your requirement, then this post is only for you.


Then solution is fancybox.net, it provide all the above features with jQuery.

Q What is Fancybox?
A fancyBox is a tool that offers a nice and elegant way to add zooming functionality for images, html content and multi-media on your webpages. It is built at the top of the popular JavaScript framework jQuery and is both easy to implement and a snap to customize.

Q. What Features it provide?
A. Following features it provide.
  • Can display images, HTML elements, SWF movies, Iframes and also Ajax requests
  • Customizable through settings and CSS
  • Groups related items and adds navigation.
  • If the mouse wheel plugin is included in the page then FancyBox will respond to mouse wheel events as well
  • Support fancy transitions by using easing plugin
  • Adds a nice drop shadow under the zoomed item 


Tuesday, 6 September 2011

jQuery Autocomplete like Facebook With Demo

jQuery Autocomplete like Facebook With Demo


jQuery facebook autocomplete live demo


Fancy facebook-like dynamic inputs with auto complete & pre added values. If you have any comments or requests, please post them and I will try to include all the requested features in the upcoming release.


Code Example:
<link charset="utf-8" href="http://www.emposha.com/demo/fcbkcomplete_2/style.css" media="screen" rel="stylesheet" type="text/css"></link>
        <script charset="utf-8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.min.js" type="text/javascript"></script>
        <script charset="utf-8" src="http://www.emposha.com/demo/fcbkcomplete_2/jquery.fcbkcomplete.js" type="text/javascript"></script>

        <h1>
JQuery Autocomplete similar to facebook</h1>
<div id="text">
</div>
<form accept-charset="utf-8" action="submit.php" method="POST">
<select id="select3" name="select3">
                <option class="selected" value="sleep">sleep</option>
                <option value="sport">sport</option>
                <option value="freestyle">freestyle</option>
            </select>
            <br />
<input type="submit" value="Send" />
        </form>
<script type="text/javascript">
          /** json_url data **/
        var jsonData=[{"key": "hello world", "value": "hello world"}, {"key": "movies", "value": "movies"}, {"key": "ski", "value": "ski"}, {"key": "snowbord", "value": "snowbord"}, {"key": "computer", "value": "computer"}, {"key": "apple", "value": "apple"}, {"key": "pc", "value": "pc"}, {"key": "ipod", "value": "ipod"}, {"key": "ipad", "value": "ipad"}, {"key": "iphone", "value": "iphone"}, {"key": "iphon4", "value": "iphone4"}, {"key": "iphone5", "value": "iphone5"}, {"key": "samsung", "value": "samsung"}, {"key": "blackberry", "value": "blackberry"}]
        /** json_url data **/
        
            $(document).ready(function(){                
                $("#select3").fcbkcomplete({
                    json_url: "http://www.emposha.com/demo/fcbkcomplete_2/data.txt",// This must be in your server
                    addontab: true,                   
                    maxitems: 2,
                    height: 2,
                    cache: true
                });
            });
        </script>
        
        <div id="testme">
</div>