JQuery Ajax

We have covered most of the basics JQuery concepts. Now is the time to learn one of the coolest JQuery feauture i.e Ajax which stands for Asynchronous JavaScript and XML. Ajax implements partial page updates. JQuery Ajax functions allow us to implement AJAX in our applications with a single line of code. Implementing Ajax via core Javascript can be cumbersome. Therefore, it is advisable to use JQuery for Ajax implementation.

AJAX Background

HTTP is a stateless protocol Whenever user interacts with a webpage and perform some action a new request is generated and sent to the server. In return server returns markup for the webpage. However, size of a webpage can be very huge and user might want to update only a small part of webpage. In such cases, it is not a good idea to reload whole page. Here Ajax can be handy as it allows only partial page upload saving huge amount of data transfer between client and server.

JQuery Load Function

JQuery uses load() function to interact with the server for data retrieval. The load() function sends request to the server and adds retrieved data to the element. It takes three parameters: url, data, and callback. The url is the file from which the load function retrieves data. This file is located on the server. The data consist of optional key-value pairs query string pairs sent to the server. Finally, callback function is the function that executes when load function completes its execution. Take a look at following example.

First create a file named “paracontent.txt” and add the following content to this file.

This is the text loaded via

Ajax

call.

The load method will load the content from this file and will place it inside the paragraph element. The complete code for the webpage including JQuery Ajax call is shown below.

<!DOCTYPE html>
<html>
<head>
    
    <title>JQuery Ajax Load</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    
    <script type = "text/javascript">
        
    $(document).ready(function(){
        $('#b1').click(function(){
           
            $('p').load('paracontent.txt', function(){
                alert('Content has been loaded');
            });
        });
    });
        
      </script>
     
   
</head>
    
<body>

    
      <button id="b1">Click to load Text via Ajax.</button>
    
    <p>This is random text</p>
    

    
    
    
</body>

</html>

Download Code Run Code

The above page contains a button and a paragraph with some random text. Clicking the button fires an event which is handled by JQuery click function. Inside the click function the load() function loads the content of “paracontent.txt” file and adds it to the paragraph element. After that the call back function executes which displays a message to the user in the alert box.

<<< JQuery Filtering FunctionsJQuery Ajax Get >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .