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
<h2> Let's learn lazy Ajax - jQuery </h2>
<p id="p1">This is Some Paragraph. </p>

My task is to get the whole text in the file
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo.txt");
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>


<button>Get External Content</button>


</body>


</html>

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


Comments

Popular posts from this blog

Missionaries & Canibal Problem in AI using Pro Log

Hide the navigation bar in jHipster Angular 2

Spring Boot - No Need to Restart the Development Server for Each Time