From Javascript to PHP and Back Again

How many times have you had to do this?

  • From Javascript, call some PHP page
  • Have PHP send back some result and/or a status message
  • Javascript checks the result and displays an error or does something with the result.

I have a new favorite way to handle this thanks to my new job and Prototype.

Here's the first part, the call from Javascript to PHP

~~~~ {.js name="code"} new Ajax.Request('dostuff.php', { method: 'get', parameters: {'param1': 'this is param 1'}, onSuccess: function(){ //do stuff }, onFailure: function(){ alert('Fail!'); }}); wzxhzdk:0

Basically what we're doing is building an associative array with status info (it could obviously have other fields besides 'status'), converting the array into JSON format, and passing back the JSON string as part of the HTTP response header.

Note that the [json_encode][] function is only comes with PHP >= 5.2 by default. If you're running < 5.2, you'll need to install the json PECL package by hand.

So what are we supposed to do with this JSON stuff we're getting back from PHP?

Here's where Prototype really simplifies things.

Let's change the onSuccess method of the Ajax call

~~~~ {.js name="code"} onSuccess: function(response, jsonHeader){ if(jsonHeader['status'] == 'Success'){ //Everything is OK, do stuff }else{ alert(jsonHeader['status']); }} ~~~~

Prototype has built-in support for parsing X-JSON headers!

All you have to do is add a jsonHeader variable to your response function and Prototype takes care of turning it back into a nice associative array for you.

What I like to do is have PHP put an explicit error message into the status variable. That way, if PHP generates an error, Javascript can just immediately do something with that error.

So there you have it. Another way using a Javascript framework can make your life easier.

Why haven't you learned one yet? It doesn't matter which one. Prototype, jQuery, etc.

Just go learn one. Right now.

I'll wait.