Intro to Ajax

Ajax is a technique which is asynchronous in nature meaning that it can be used to send data to server and fetch data from server in the background without refeshing the page or changing the display. There are many ways to write Ajax code like using python, javascript or jquery.

In this tutorial, we are going to use Jquery for Ajax functionality.

The syntax for writing Ajax in Jquery is

$.ajax({
        type: 'GET',
        url: 'ajax.php',
        data: {var1:variable1, var2:variable2},
        beforeSend:function(){
            alert("Before sending");
        },
        success:function(data){
            alert("Successful");
        },
        error:function(){
            alert("Error");
        }
});

Here,

  • Type – It is similar to method used to send data in PHP. It can be GET or POST.
  • URL – The link to the page or the document where the script that we need to run is written. The script can be used to contact a server in the background or it might simply have some elements which we want to display when for instance, a button is clicked. This can even be simply a text file which we want to display when user clicks a button.
  • Data – The data which is sent to the script in the other file running in the background.
  • beforeSend – Function executed before sending the script.
  • success – Function executed if the script is successful.
  • error – Function executed if some error occurs.

However, using this syntax is not always necessary. If we want to simply load a text file by clicking a button, then we do not need to send any data or create any beforesend or success functions.

Load Text File Using Ajax

In the code below, we will see how to load an external text file in the page without refreshing or reloading the page. Here, the contents of the text file are loaded inside the div element on clicking the button Get External Content.

<html>
<head>
    <script src="jquery.min.js"></script>
    <script>
        $(document).ready(function(){
                $("button").click(function(){
                        $("#div1").load("test.txt");
                });
        });
    </script>
</head>
<body>

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
    <button>Get External Content</button>

</body>
</html>

The contents of the div element with id div1 are replaced by the contents of the text file on clicking the button.

Before clicking the button

before clicking the button

After clicking the button, the text file is loaded

text file loaded after clicking the button

Please feel free to download the source code for reference.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No