Triggering PHP with jQuery (AJAX)

25 07 2010

In JavaScript Triggering PHP Without Page Reload, I examine the old-fashioned way of having JavaScript get a response from PHP by using an iframe element. Now with AJAX, particularly AJAX as made available in jQuery, it’s a breeze to have JavaScript and PHP interact. The best part is that much less code is necessary and cross-browser scripting is far easier. Here are the results of tweaking the previous HTML, JS and PHP files and bringing them up to modern standards:

<head><title>devshed exp</title>
<button id="mybut" accesskey="C">Click me</button>
<script type="text/JavaScript" src=""></script>
<script src="devshed3.js" type="text/javascript"></script>

Notice that the iframe is gone!

As you will note, I am running jQuery from Google and thereby conserve my webserver’s space for other things. Is this a good idea? Is it really smart to give one company that much trust and power? I raise these questions for your consideration, as we move on to review the next file:

The PHP:

class ClrChange {
     private $res;
	 public function __construct( $res ) {
	     $this->res = $res;
	 public function toggleColor() {
	      return !$this->res;         // boolean
$bgc = "";
$strClrs = null;

if (isset($_GET['bgcolor'] )) {
	$bgc = htmlentities( $_GET['bgcolor'] );

if (isset($_GET['colors'] )) {
	$strClrs = htmlentities( $_GET['colors'] );

$clrs = array_flip( explode("|",$strClrs) );   // exp: pink => 0, lavender => 1

$o = new ClrChange( $clrs[$bgc] );
$res = (int) $o->toggleColor();      // cast boolean to int to see true/false as 1 and 0
echo $res;

I deleted the first two lines of the previous PHP file, getting rid of ob_start() which aids the execution of the next line which consists of a header() statement. Removing the iframe, however, renders the whole purpose of using the header() irrelevant and so I removed it.

The final result from the PHP code, I will store in a variable, using AJAX instead of the iframe. If you are uncertain how to use jQuery’s AJAX feature, check out

The JS file:
var clrs = new Array('99ffff','ff9999');
// initial target url
var target_url = "devshed3.php?bgcolor=" + escape(clrs[1]) + "&colors=" + clrs[0] + escape("|") + clrs[1];
function DoAjax() {
var bgc = "";
url: target_url,
success: function(html){
bgc = html;
$("#mybut").css("backgroundColor", clrs[bgc]);
// update the target url
target_url = "devshed3.php?bgcolor=" + escape(clrs[bgc]) + "&colors=" + clrs[0] + escape("|") + clrs[1];
function() {
DoAjax(); // on page load

I set up two global variables, one containing an array of colors that can contain either named color values or hexcodes. The other variable is the initial target url, a PHP script. When the page loads a function DoAjax() executes and the button appears with a colored background.

DoAjax() is a function that employs jQuery’s AJAX support. I specify the target url and what should happen after the PHP code executes and the jQuery successfully retrieves the result. I assign the result to variable bgc and use the variable as an index into the colors array to change the button’s background. Lastly, the target url needs to be updated so subsequent clicks toggle the background color.

This example uses very basic jQuery code and yet you may find it challenging if you are accustomed to JavaScript coding maneuvers. Consider the following snippet which sets up an event handler in JavaScript:

document.getElementById('mybut').onclick = DoAjax;

This code says that when the button’s click event occurs, invoke DoAjax ito handle that event.

In jQuery setting up the button’s click event handler requires a different way of coding, as follows:
$("#mybut").click(function() {

While the above snippet gives the impression as if one were programmatically forcing a click of mybut, such a conclusion would be incorrect. In truth, mybut’s click event is being forced to bind with an anonymous function whose definition encompasses in this case invoking DoAjax(). Later, if you wished to trigger that event, you would use the following code:


Clearly, only when the click method is invoked without any parameters, will the specified click handler actually execute.

This work is licensed under a Creative Commons License



2 responses

28 07 2010
William Estrada

re: Your jquery from google question, I think it is a matter both speed and preference.

Speed, you are using Google’s Content Delivery Network (for free). If your host is located in New York and a user visits from California, the CDN will feed the user the JQuery file from a closer location to California where your JQuery file would only be coming from New York for everyone around the world.

Cache, it is likely that the user’s browser would have cached the file sometime during the course of browsing other sites before visiting your site. One less initial hit on their first visit to your site.

Browsers by default are set to only so many concurrent download connections from a particular hostname. Using Google gives you one less concurrent download to your hostname.

Preference wise, depends on what you feel about Google from a personal and security standpoint or maybe you have a client who demands everything be on their servers no matter what.

29 07 2010
Sharon Lee Levy

Thank you for stopping by and sharing your thoughts.

Yes, presently Google’s CDN is free, but there is no guarantee that it will remain so. Should a business take the risk that Google may at any time decide to charge a fee? If Google were to charge, perhaps the business might choose to host jQuery on its own web server. In such a case, how costly would such an undertaking be?

Your point about the location of the host vs. the location of Google’s CDN is well-taken. Of course, when a browser accesses a hostname, that involves a DNS lookup. Google actually recommends that you minimize DNS lookups (see as does Yahoo (see The recommendations of both these titans indicate that serving up a web page involves balancing DNS lookups against parallel downloads.

Your point about the likelihood that “… the user’s browser would have cached the file sometime …”, contradicts Yahoo’s conclusion, based on the research of a blogger at Yahoo claims that “40-60% of daily visitors to your site come in with an empty cache. (see”

In view of your comment about browsers and the number of permissible concurrent downloads, I’d like to suggest a previous post in which I cover this important topic in Simultaneous HTTP GET Requests.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: