Thursday, January 22, 2009

Super Simple AJAX Forms with jQuery and JSON : dataservice.php

Our last installment of the Super Simple AJAX Forms with jQuery and JSON we cover the server side of things. The dataservice.php file covers the business logic behind the web form. Like the webpage.html I boiled this down to the smallest and most reusable code possible.


The very top of the file contains MySQL setup code for connecting to the database. If this is not familiar by now then this tutorial is probably a bit over your head anyhow. In any case set that up, i'm not going to cover it in detail here. Let's get to the meat of our discussion.

PHP Parameters
 <br />// Make sure we have a full Request<br /> if(!isset($_REQUEST['action']) || !isset($_REQUEST['id'])){<br />  echo "Invalid Request";<br /> exit(0);<br /> }<br /><br />// Which action do we take?  If we dont find one we do nothing.<br /> if($_REQUEST['action']=='getuser')<br /> getUser((int)$_REQUEST['id']);  // sanitize  ID by converting to int<br /> if($_REQUEST['action']=='update')<br /> updateUser((int)$_REQUEST['id']);  // sanitize  ID by converting to int<br />

This code is straightforward. We simply make sure we have our unique key (id) and our action (something to do). If we do we proceed to map the parameter action to a function we'll call. We sanitize the ID coming in to prevent SQL injection.


getUser() function
 <br />// Get User Method<br />function getUser($id){<br />  $query  = "select * from users where uid=".$id;<br />  $result = mysql_query($query);<br />  while($row = mysql_fetch_array($result, MYSQL_ASSOC)){<br />  $records[]= $row; // Push into array all records<br /> }<br /> if(!isset($records))<br />  echo "[{error:'No Records Found',status:'error'}]";<br /> else<br />  echo json_encode($records); // Encode everything from SQL<br />  /*<br />   * If you dont have php 5, or pear installed on your host<br />   * check out http://mike.teczno.com/json.html<br />   */<br />}<br />

This function is called when we load our webpage.html. It's called by the jQuery ready() in the HTML. You can see here, it is a very simple query, then we push the result set into an array. I do this in the example to show that with JSON you can have multiple row results in the response going back. That way you can even persist the data locally and re-use it when you need to. If we have a result set we call json_encode() with our records. This turns it into JSON that we read with javascript on the browser side.


So really, all we do here is build a JSON string out of our MySQL resultset. The big key is to understand that this is stored in a JSON array. You need to get a good understanding of JSON to be effective with this sort of application. Once you do it all falls in line. Basically a JSON array is a container of JSON objects. Check out Introducing JSON for more details.



Now, you may not be on PHP5 which has json_encode() natively. So I put in here a link to the source code for a JSON encode function. Pear also has this type of library but depending on your web host situation you may need to fall back on the JSON.php file itself.


updateUser() function
 <br />function updateUser($id){<br /> // Build update statement<br /> $sql="";<br /> foreach($_REQUEST as $key => $value){<br />   if(strpos($key,"FLD_")!==false){ // Something to post<br />    $sql.=str_replace("FLD_","",$key)."='".mysql_real_escape_string(stripslashes($value))."', ";<br />   }<br />  }<br /> $sql="update users set ".substr($sql,0,-2)." where uid=".$id;<br /> // Update<br /> mysql_query($sql);<br /> // Check for an updated record<br /> if(mysql_affected_rows()>0){<br />  echo "{status: 'OK'}";<br /> }else{<br />  echo "{status: 'Update Failed '}";<br /> }<br /><br />}<br />

Finally, our update statement. This is as simple as our process for filling the FLD_ in the webpage.html file. We scan the entire $_REQUEST array for any FLD_ and then post those to our database string. It works just like how we built our queryString in the webpage.html post. We set the values to update, then we runs the mysql_query() to update records.


Take note of a few things here. First we strip off the FLD_ prefix. We also sanitize the input data by stripping out slashes and escaping special characters for mysql. Again this is to prevent SQL injection. I see many people who don't do this with AJAX services and thus are very open to attack on their back end. I also pull off the last ", " off the end of the update statement.



We last check to see we updated a row or we return an error. The webpage.html code looks for the OK, so if we don't have it then we display the error.


That is it. You should be able to use this as an example and start to your own AJAX code. Remember this is a learning example and that you should make sure you have far better error checking and recovery from SQL errors. You might also want to adapt this code for an insert statement or a delete statement to have full CRUD updates to your database.


My purpose here was to show you that asynchronous web calls are not that complicated with the right library (jQuery). Now get out there and write some code!

3 comments:

outsource seo said...

Modifying the parameters will adjust the code functions.

seo reseller said...

If you change the parameters will this requires to change it code functions ?

Rob said...

Remember, we look for FLD_ as the values for the fields. So if you modify it then you'll need to change the way you pick it up.