How to make a simple AJAX call with JQuery

AJAX Stands for "Asynchronous JavaScript and XML".

Basically we use AJAX to change parts of our web page with loaded data from the server  without reloading the whole page. Google, YouTube, Facebook all use AJAX to display changing data.

What happen in AJAX is we can request HTML,TEXT, XML results from a server using HTTP GET or POST requests and load the response to selected HTML elements in our web page.
JQuery load() method can be easily used to make a AJAX call to server.

HTML code.

<!DOCTYPE html>
<html>
<head>
    <script src="Scripts/jquery-1.11.3.js"> </script>      
</head>
<body>
<div id="div1"> <h2> Let jQuery AJAX Change This Text </h2> </div>
<button>Get External Content</button>         
    <script>   
        $(document).ready(function(){
            $("button").click(function(){
                $("#div1").load("demo_test.txt");
            });
        });                    
    </script>     
</body>
</html>

When you click the button JQuery load() method will load the content of the file demo_test.txt to div element which has ID div1.

NOTE:

  1. If your txt file need to load is not in the same directory as html file you have to give a relative path to the file in to the load method (eg: "Files/demo_test.txt")
  2. If you don't have have a internet connection when you run this example you have  to manually download the JQuery and give the path to JQuery path.

No comments:

Post a Comment