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.
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>
-
-
$(document).ready(function(){
-
-
$(":submit").click(function(e){
-
-
e.preventDefault();
-
-
$.post(
-
"ajax.php", //the php script we send the ajax request to
-
$("form").serialize(), //serialize the data from the form
-
function(data){ //the function to execute ajax success
-
//data in this case is a json object
-
//here we are filling in the table data
-
//with data from the database.
-
//you can see how json works in javascript if
-
//you've never used it before.
-
$(".name").html(data.name);
-
$(".street").html(data.street);
-
$(".city").html(data.city);
-
$(".state").html(data.state);
-
$(".zip").html(data.zip);
-
},
-
"json" //the data sent back is json
-
);
-
-
});
-
-
});
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
-
$host = "localhost";
-
$username = "put_your_username_here";
-
$password = "put_your_password_here";
-
$db = "put_your_db_here";
-
$table = "put_your_table_here";
-
-
$con = mysql_connect($host, $username, $password);
-
mysql_select_db($db);
-
-
/* Get the row sent through the ajax call from the database */
-
$sql = "SELECT * FROM $table WHERE ID = " . $_POST['number'];
-
$row = mysql_fetch_assoc(mysql_query($sql));
-
-
/* Encode the result in JSON. This makes it easy
-
* to process in javascript. */
-
$json = json_encode($row);
-
-
/* Send it back to the javascript */
-
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!