JQuery Ajax Get

In the last article we saw what Ajax is and how it works. We saw how Load method was used to asynchronously load data from any resource on the server without complete page load. There are other ways to get data asynchronously from server via Ajax. JQuery contains Ajax Get and Post method for such purposes. This article provides a brief introduction to both Get method.

Ajax Get Function

The get() function in JQuery requests data from any particular source on the server. This resource can be a JSON object, a text document or virtually anything. The get() method uses HTTP get request to request data from a server. It is important to note that get method may also return already cached data. The get() method takes two arguments: first one is the URL of the resource you want to request from the server and the second parameter is the call back function. Take a look at following example.

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

This is the text loaded via

Ajax

call.

The get() 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 get() 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 code contains a button and a paragraph. Button click fires an event. JQuery click event handler handles this event. Inside the event handler get function executes and retrieves data from a text file. JQuery factory function selects paragraph and sets the html of the paragraph to the data returned by the server. As a result, when user clicks the button, the content of the paragraph elements are updated asynchronously via Ajax.

<<< JQuery AjaxJQuery UI Draggable-Droppable >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .