Ajax jQuery.ajax method

The jQuery.ajax() method is a powerful feature in jQuery that helps you communicate with the server without reloading the whole webpage. This is very useful when you want to send or receive data in the background and update only a part of the webpage — making the user experience faster and smoother. Using the type property, you can tell the browser what kind of request you're making, like a GET request (to fetch data) or a POST request (to send data). The url property lets you define where this request should be sent — in other words, the location of the server file or API you want to connect with. You can also include information you want to send to the server using the data property. For example, if a user fills out a form, that data can be sent to the server using this method. Additionally, the dataType property tells jQuery what kind of response to expect from the server — whether it will return plain text, HTML, JSON, or something else. Overall, $.ajax() gives you full control over how the browser talks to the server, what data is sent, what to do with the response, and how to handle errors — all without refreshing the page. jQuery.ajax() method example


<html>
<head>
    <title>Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<input type="text" id="stud_name" placeholder="Enter student name">
<button id="submitStudBtn">Save</button>
<div id="message"></div>

<script>
$("#submitStudBtn").click(function(){
  var studName = $("#stud_name").val();

  $.ajax({
    type: "POST",
    url: "save_student.php",
    data: { studName: studName },
    success: function(response){
      $("#message").html("Response: " + response);
    },
    error: function(){
      $("#message").html("Error occurred.");
    }
  });
});
</script>

</body>
</html>