Nifty PHP/AJAX tricks

These are a couple awesome AJAX/PHP tricks I learned to make coding just slightly easier on myself.

Exit

Lets say we had an index page, and when the user click a button, it would display the time. Typically, in the past I would have it go to another “remote procedure call” (RPC) page, like “time.php” where the main portion of the script would be “echo time();”. This tends to clutter my folders with miscellaneous scripts if I have multiple AJAX events. I may have a different RPC for every page, which could mean I have like 50 php files in one folder and I’m not sure which ones are the RPC and which ones are the main files.

I then started condensing them, making one large script for a few files, and using a $_POST['action'] to decide what to do. So if I had an ajax.php page it might look something like this:

<?php
if($_POST['action']=='time'){
   echo time();
}else if($_POST['action']=='hello'){
   echo "hello!";
}?>

So now it will execute the portion of the script that it is told. So if I point my AJAX to ajax.php and pass a post variable called “action=time”, it will return the time. We have now condensed it slightly.

We can condense it even further by using the php function “exit();”. This function completely stops (exits) the script. If my script looked like this:

<?php
echo "hello ";
exit();
echo "world!";
?>

The output would look like this: hello
Exit will abort the script and not run anything after it.

Exit also has the capability to display (echo) a message as to why it is quitting, so you could essentially use exit() and let people know they aren’t logged in if you wanted. Here is an example:

<?php
session_start();
$notlogged="<a href=\"login.php\">Please log in to view this page</a>";
if(!$_SESSION['loggedin'])
   exit($notlogged);
/* Main Content Starts Here */
?>

So if we had never logged into the site, all we would see is “Please log in to view this page” as a link that we could click.

Lets put this all together. The exit function allows you to point the ajax script to the current page, as it will “exit” and echo the data you want without running the main content of the page over again. Let me show you what I mean, using jQuery ajax, with a time.php.

<?php
//time.php
if($_GET['do'] && $_GET['do']=='time')
   exit(date('g:i A'));
if($_GET['do'] && $_GET['do']=='hello')
   exit("Hello World!");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX Example</title>
<link type="text/css" href="css/custom-theme/jquery-ui-1.7.2.custom.css" rel="stylesheet" />	
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.geturlparams.js"></script>
<script type="text/javascript">
$(function() {
	$('#checktime').click(function(){
		$.get('time.php',
			{do:'time'},
			function(data){
				$('#timeorhello').html(data);
			});								 
	});
	$('#sayhello').click(function(){
		$.get('time.php',
			{do:'hello'},
			function(data){
				$('#timeorhello').html(data);
			});								 
	});
});
</script>
<body>
<div id="timeorhello">&nbsp;</div>
<input type="button" id="checktime" value="Get Time" />
<input type="button" id="sayhello" value="Say Hello" />
</body>
</html>

Pretty simple stuff right? You can reduce the number of extra files by simply putting the AJAX commands at the top of the file. If you put “echo(time());”, it would continue to run the entire page and mess up your AJAX. This has made my life easier and my code a little more succinct.

Arrays

Because AJAX only accepts strings to be echo, and returned to the AJAX function, so a lot of people struggle with returning an array to Javascript through AJAX. There are 2 ways to do this that don’t require JSON.

The first is simply to break the array up and make it into a string using the “implode” function:

<?php
$array[1]="hello";
$array[2]="world";
$array[3]="!";
$newarray=implode("::",$array);
echo $newarray;
?>

On the Javascript end, just split it up into an array again!

var myArray=data.split('::');

That is by far the easiest way to return arrays.

There is one problem. What if in PHP, your arrays didn’t have numerical keys, but strings: $array['name']='bob'. This is where we run into a problem. There is a way around this fairly easy. Most languages have an “evaluate” command, which will take a string, and execute it as though it were code. In PHP and Javascript, it is eval(). Here is a PHP example: eval("echo 'Hello World!';");. This would output “Hello World!”. In Javascript, it is exactly the same thing. So lets use eval() to return a Javascript array!

<?php
$array['name']='bob';
$array['age']='96';
$array['sex']='male';
$return='var myArray={"name":"'.$array['name'].'", "age":"'.$array['age'].'", "sex":"'.$array['sex'].'"};
echo $return;
?>

And on the Javascript side, all you need to do is evaluate the string:

function handler(data){
   eval(data);
   alert(myArray['name']);
}

Its a bit lengthy to do it this way, but will definitely get the job done. One thing to watch out for would be quotes, plus signs, slashes, especially if the user gets to define some of the stuff that is being returned.

I hope this has helped out a little with using PHP and AJAX. I spent hours trying to figure this stuff out the first time, but when I did, it made my life a lot simpler.