PHP and Ajax Integration With Ease
by MikeRWeb programmers are constantly faced with new challenges. Somewhat recently I faced a new challenge. One of my clients wanted a more desktop-like application feel to his administration panel for a high-traffic e-commerce web-site. This meant turning to ajax and php. ajax is short for “Asynchronous Javascript and XML”. Don’t panic, it’s not as complicated as it may seem.
You make Javascript create an XMLHttpRequest to a php script, which in turn returns the plain text or XML data back to Javascript. That’s correct, despite the “XML” portion of “ajax“, you are not by any means required to use XML. In fact, for simple ajax operations I rarely opt to use XML! Another issue that web programmers face daily is the need to get applications developed quickly. Thankfully, there is a very nice framework called “ajax Gold” available to the public courtesy of Dummies.com! http://media.wiley.com/assets/1002/24/ajaxcode.zip
Creating ajax functions using the ajax Gold framework is extremely easy. In fact, all you have to do is call getDataReturnText(”url_to_script.php”, callback_function);
1.) Define event handler (ie: onClick for a button)
2.) Set event handler to call the function you just wrote
3.) Inside the event handler, make the necessary getDataReturnText(…) call specifying the callback function that you’re going to create
4.) Create the callback function
5.) Test!
The following is a sample ajax/PHP script:
<script language=”javascript” src=”ajaxgold.js” mce_src=”ajaxgold.js”></script>
<script language=”javascript”>
<!–
function SuspendUser(user_id) {
getDataReturnText(”suspend_user.php?user_id=”+user_id, CB_SuspendUser);
}
function CB_SuspendUser(text) {
document.getElementById(”response”).innerHTML = text;
}
–>
</script>
<!– html goes here –>
<span id=”response”> </span>
<input type=”button” value=”Suspend User” onclick=”SuspendUser(50);”>
<!– rest of html goes here –>
And the php script would simply pull $_REQUEST[’user_id’] and perform the desired action for that user id (suspend the user).
Whatever is printed from the php script will automatically appear in your web-page where the SPAN tag is.
As you can see, it’s quite simple! More to come so check back often.
Technorati Tags: Programming Tools

