Calling PHP in dynamic pages

September 28, 2009

Here’s a great little piece of code I came across today – it gives us a way to access server-side data and functions from a live javascript page.  There are so many things that javascript cannot do for security reasons, but by using this code snippet, you can call any PHP script from your webpage, have them execute whatever you need and then use the output in your webpage.  So much of AJAX is way more complex than this – if you’re looking for a simple solution, this could be it!

Loading and Saving Files –

function IO(U, V) {//LA MOD String Version. A tiny ajax library. by, DanDavis var X = !window.XMLHttpRequest ? new ActiveXObject(‘Microsoft.XMLHTTP’) : new XMLHttpRequest(); ? ‘PUT’ : ‘GET’, U, false ); X.setRequestHeader(‘Content-Type’, ‘text/html’) X.send(V ? V : ”); return X.responseText;}

In my application, I have a list of transactions from a database, clicking on the delete image calls a javascript event handler which calls the above script. The IO url is deletrans.php and it returns a success message once the transaction has been deleted, then the last part of the javascript routine updates the transaction table.

So I have this onclick javascript:

function deletetrans(trans_id) {
var answer = confirm(“Are you sure you want to delete this transaction?”);
if (answer){
msgbox(IO(‘deltrans.php?transid=’ + trans_id), ‘red’);
} else {
msgbox(“Deletion cancelled”, ‘green’);
return null;

And my PHP file is:

include ‘modules/config.php’;
include ‘modules/db_open.php’;

$db = db_open();
$sql = “delete from `entries` where `entry_id` ='{$_GET[‘transid’]}’ limit 1;”;
if (!$result=mysql_query($sql,$db)) die (“Could not delete this transaction”);
echo “Transaction {$_GET[‘transid’]} deleted!”;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: