Open In App

jQuery ajax() Method

jQuery Ajax() method is used to send Ajax requests or asynchronous HTTP requests to the servers for fetching and posting data according to the requirement by specifying the request type.

Syntax:

$.ajax({name:value, name:value, ... })

Parameters: The list of possible parameter that can be passed to an Ajax request are listed below:



Example 1: This example use ajax() method to add the text content from outer text file by sending ajax request.




<!DOCTYPE html>
<html>
 
<head>
    <title>
        jQuery ajax() Method
    </title>
 
    <script src=
    </script>
 
    <script>
        $(document).ready(function () {
            $("li:parent").css("background-color", "green");
        });
    </script>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green">
        GeeksForGeeks
    </h1>
 
    <h2>
        jQuery ajax() Method
    </h2>
 
    <h3 id="h11"></h3>
 
    <button>Click</button>
 
    <!-- Script to use ajax() method to
        add text content -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "geeks.txt",
                    success: function (result) {
                        $("#h11").html(result);
                    }
                });
            });
        });
    </script>
</body>
 
</html>

geeks.txt

"hello geeks !"

Output:



Example 2: This example illustrates the ajax() method in jQuery.




<!DOCTYPE html>
<html>
 
<head>
    <title>jQuery ajax() Method</title>
    <script src=
    </script>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksForGeeks
    </h1>
    <h2>jQuery ajax() Method</h2>
    <h3 id="h11"></h3>
    <button>Click</button>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "geeks.txt",
                    success: function (result) {
                        $("#h11").html(result);
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            });
        });
    </script>
</body>
 
</html>

geeks.txt

GeeksforGeeks,
A Computer Science Portal for all Geeks.

Output:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.


Article Tags :