jQuery Ajax Tutorial and Example | PHP Tutorial For Beginners

What is jQuery?

jQuery is a lightweight JavaScript library whose motto is "write less, do more." It simplifies DOM manipulation, event handling, animations, and Ajax — turning many lines of JavaScript into a single method call.

What is AJAX?

AJAX (Asynchronous JavaScript and XML) allows web pages to update a portion of their content without reloading the entire page. The browser sends a request in the background and updates the DOM with the response.

jQuery + AJAX Together

jQuery's $.ajax() method provides a clean, cross-browser API for making AJAX requests — handling form data, JSON responses, and callbacks far more easily than raw XMLHttpRequest.

This example uses two files. school.php contains the form; details.php handles the AJAX request and queries the database. You will need a MySQL database named school with a students table containing name, rno, and address columns.

Step 1 — Create school.php

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  function getdetails() {
      var name = $('#name').val();
      var rno  = $('#rno').val();
      $.ajax({
          type: "POST",
          url:  "details.php",
          data: { fname: name, id: rno }
      }).done(function(result) {
          $("#msg").html("Address of Roll No " + rno + " is " + result);
      });
  }
  </script>
</head>
<body>
  <table>
    <tr>
      <td>Your Name:</td>
      <td><input type="text" name="name" id="name"></td>
    </tr>
    <tr>
      <td>Roll Number:</td>
      <td><input type="text" name="rno" id="rno"></td>
    </tr>
    <tr>
      <td></td>
      <td>
        <input type="button" value="Submit" onclick="getdetails()">
      </td>
    </tr>
  </table>
  <div id="msg"></div>
</body>
</html>

Step 2 — Create details.php

<?php
$name = $_POST['fname'];
$rno  = $_POST['id'];

$con    = mysql_connect("localhost", "root", "");
$db     = mysql_select_db("school", $con);
$sql    = "SELECT address FROM students
           WHERE name='" . $name . "' AND rno=" . $rno;
$result = mysql_query($sql, $con);
$row    = mysql_fetch_array($result);

echo $row['address'];
?>

Note: The key difference here compared to a normal form submission is that you get the result without refreshing the page — that is the magic of jQuery Ajax.

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →