jQuery- Ajax Fast Track

Today I have decided to refresh my knowledge in Ajax with jQuery. The fantastic and easiest way to communicate with server script is using the Ajax Scripts. 

What is Ajax?
Ajax is Asynchronous JavaScript and xml. This is used mainly to exchange data to server and refresh the particular part of the webpage. 

Today most of the web and mobile applications are using the Ajax to communicate with the server. I also love Ajax to use in my applications.

Why jQuery?
Without jQuery Ajax is bit tricky – mean need to write more. I am a lazy guys always find the short way to reach the goal. Lets’ dig Ajax via jQuery 🙂

jQuery-Ajax load() method
Function :- Loading the data from the server and put into a particular element. 
Example : Let’s get the data from a file called from demo.txt
This is the demo.txt file

Let’s learn lazy Ajax – jQuery


This is Some Paragraph.



My task is to get the whole text in the file



https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js

$(document).ready(function(){
    $(“button”).click(function(){
        $(“#div1”).load(“demo.txt”);
    });
});




Let jQuery AJAX Change This Text



Get External Content






Note: This is the first discussion therefore I have show whole code. Next sessions we discuss short codes 🙂

Okay! Guys Is there any way to get the particular element data in the demo.txt file? Yes! of course, If we want to get content of id ‘p1’. Here is the way…

$(“#div1”).load(“demo.txt #p1”);

Now we dig more on load. We also use call back functions to do some work when the load method is completed. 

$(“button”).click(function(){
    $(“#div1”).load(“demo”, function(responseTxt, statusTxt, xhr){
        if(statusTxt == “success”)
            alert(“External content loaded successfully!”);
        if(statusTxt == “error”)
            alert(“Error: ” + xhr.status + “: ” + xhr.statusText);
    });
});


jQuery-Ajax get & post Methods
get and post method are used to request the data from the server in HTTP GET and POST requests.

I assume you have know HTTP methods

I directly jump into the implementation of both methods

get method
$(“button”).click(function(){
    $.get(“demo.php”, function(data, status){
        alert(“Data: ” + data + “\nStatus: ” + status);
    });
});


post method
$(“button”).click(function(){
    $.post(“demo_test_post.asp”,
    {
        name: “Donald Duck”,
        city: “Duckburg”
    },
    function(data, status){
        alert(“Data: ” + data + “\nStatus: ” + status);
    });
});


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s