Easy ajax with jQuery and PHP

March 29th, 2010

When I was first learning about web programming, it was difficult to grasp how javascript can interact with PHP.  How do I manipulate data in the database with a client-side language?  The answer, of course, is ajax, and if you’ve never used ajax, now is the time to learn how.

What is ajax?

Ajax is not a singular technology, it is a collection of technologies used for asynchronous communication between the client and server i.e. javascript grabbing data from a PHP script and displaying it on the page without refreshing the page.  This is done through a DOM api called XMLHttpRequest, and I would encourage you to read a more in-depth view on its Wikipedia page.  While this has some SEO implications, it also gives the programmer or designer a way to build rich, dynamic internet applications that don’t require a propriety plugin like Flash or Silverlight.  Now that you have a basic understanding of ajax, lets try it out.

In this tutorial and demonstration, I will take a number from the user with an input box, and grab the row with that ID from the database and display it.  This is not a useful example, but it does demonstrate the principles of moving data back and forth between the client and the server, and how we can display the data.

View the demo

 

Database Scheme

CREATE TABLE IF NOT EXISTS `demo_easy_ajax` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(45) NOT NULL,
 `street` varchar(45) NOT NULL,
 `city` varchar(45) NOT NULL,
 `state` varchar(2) NOT NULL,
 `zip` varchar(5) NOT NULL,
 PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Our database table is going to be contact addresses with the fields ID,  name, street, city, state, and zip.  You can run this code in your database management software or however you want, as long as the scheme is correct.  Make sure to fill in the table with values!

Javascript (and HTML)

     <form action="index.php" method="post">
       <input type="text" name="number">
       <input type="submit" name="submit" value="Get Row">
     </form>
     <table>
       <tr>
         <td>Name</td>
         <td>Street</td>
         <td>City</td>
         <td>State</td>
         <td>Zip</td>
       </tr>
       <tr>
         <td class="name"></td>
         <td class="street"></td>
         <td class="city"></td>
         <td class="state"></td>
         <td class="zip"></td>
       </tr>
     </table>
  1.  
  2. $(document).ready(function(){
  3.  
  4.   $(":submit").click(function(e){
  5.  
  6.     e.preventDefault();
  7.  
  8.     $.post(
  9.       "ajax.php",  //the php script we send the ajax request to
  10.       $("form").serialize(),  //serialize the data from the form
  11.       function(data){  //the function to execute ajax success
  12.          //data in this case is a json object
  13.          //here we are filling in the table data
  14.          //with data from the database.
  15.          //you can see how json works in javascript if
  16.          //you've never used it before.
  17.          $(".name").html(data.name);
  18.          $(".street").html(data.street);
  19.          $(".city").html(data.city);
  20.          $(".state").html(data.state);
  21.          $(".zip").html(data.zip);
  22.        },
  23.       "json" //the data sent back is json
  24.      );
  25.  
  26.    });    
  27.  
  28.  });

I’m using jQuery to do the actual ajax call.  I do this because it’s a lot of code to do so by hand, and javascript frameworks are all the rage today.

PHP

/* Connect to the database */
  1. $host = "localhost";
  2. $username = "put_your_username_here";
  3. $password = "put_your_password_here";
  4. $db = "put_your_db_here";
  5. $table = "put_your_table_here";
  6.  
  7. $con = mysql_connect($host, $username, $password);
  8. mysql_select_db($db);
  9.  
  10. /* Get the row sent through the ajax call from the database */
  11. $sql = "SELECT * FROM $table WHERE ID = " . $_POST['number'];
  12. $row = mysql_fetch_assoc(mysql_query($sql));
  13.  
  14. /* Encode the result in JSON.  This makes it easy
  15.  * to process in javascript. */
  16. $json = json_encode($row);
  17.  
  18. /* Send it back to the javascript */
  19. echo $json;

The php code is responsible for pulling data from the database, and sending it back to the javascript to be processed.  Although ajax was named because it originally used XML as its data exchange format, it doesn’t have to use XML as its data exchange format.  Instead, I will use JSON.  PHP and javascript both handle JSON natively and easily, and JSON will let us map the table fields and values exactly to the key value pairs sent to the javascript.

The end!

That’s all there is to it!  Once you understand what ajax is capable of, you can use it for a variety of tasks.  For example, in my most recent project, the ability to remove items from the shopping cart is completely ajax.  Ajax is very capable of making very intuitive user interfaces.

Remember, in this example, there is no validation or security checking.  It is imperative that you check your inputs before you do any querying to your database!

In the future, I will have some more specific use-cases for ajax (with tutorials!)  In the meantime, if there are any specific uses for ajax that you just can’t figure out, leave a comment and I’ll either help you with it, or write a tutorial that you can follow.  I’d love to hear from you!

Leave a Reply