Return Multiple Values From Ajax Using MooTools and PHP

Written by David Walsh on Wednesday, August 20, 2008


This article may feature code that is no longer best practice in MooTools.
Click here to learn what has changed to make your code framework-compatible.

Unfortunately, PHP/Ajax interactions can only return one value. I want to show a trick that I’ve used with Ajax that allows for multiple values to be returned to the page.

Lets assume that we have a basic Ajax request made to a PHP script. We’ll want a success/error switch as well as a success/error message. For example, “You have successfully submitted your email address” or “Your email address is not valid. Please try again.” Those are great messages but provide no success or error code. And if there is an error (represented by 0), wouldn’t you want a detailed message?

What I do is separate returned values using a “|”. You can choose whatever delimiter you like.

The PHP

	/* bunch of processing up here */
	
	if($success) {
		return '1|You have successfully submitted your email address.';
	} else {
		return '0|Your email address is not valid.  Please try again.';
	}
	

Now, lets look at the MooTools.

The MooTools 1.2 Javascript

	
	/* inside the ajax object....*/
	onComplete: function(response) {
		//get vars
		var parsed = response.split('|');
		var code = response[0];
		var message = response[1];
		
		//actions
		if(code) { //success!
			
			// do success stuff
			
		} else { //no good
			
			// do error stuff, show detailed message
			
		}
	}
	

Since we have both a code and the message, the code is used for the basic “good or bad” value and the message provides detail. How do you do things?


Follow via RSS Epic Discussion

Commenter Avatar August 20 / #
Dr.Death says:

i use something like this

$result['result'] = TRUE;
$result['id'] = 12;
$result['avatar'] = ‘bla.jpg’;
$result['name'] = ‘bla’;
$result['time'] = 121212121212;
$result['text'] = ‘text’;
$result['type'] = 2;
die(json_encode($result));

options = {
url: ‘/ajax/file.php’,
data: somedata,
onSuccess: function(result) {
if(result['result']) dosuccess
else if(result['errors']) do errors
}
};
new Request.JSON(options).send();

Commenter Avatar August 20 / #
thomasd says:

Normally I use JSON to send data between client and server.
With JSON you can encode a whole array and send it to the client or server and there you decode it.

So your example could look like this:

The PHP:

/* bunch of processing up here */

if($success) {
$status = array(‘code’ => ‘1′, ‘message’ => ‘You have successfully submitted your email address.’);
} else {
$status = array(‘code’ => ‘0′, ‘message’ =>’Your email address is not valid. Please try again.’);
}
//json_encode() requires PHP5
return json_encode($status);

The Mootools 1.2 Javascript

/* inside the ajax object….*/
onComplete: function(response) {
//get vars
var status = JSON.decode(response);

//actions
if(status.code) { //success!
alert(status.message);
// do success stuff

} else { //no good

// do error stuff, show detailed message
alert(status.message);
}
}

or even better using Request.JSON:

/* inside the ajax object….*/
onComplete: function(status) {
//actions
if(status.code) { //success!
alert(status.message);
// do success stuff

} else { //no good

// do error stuff, show detailed message
alert(status.message);
}
}

Did I say that I love Mootools? :)

Commenter Avatar August 20 / #
Nacho says:

i always use JSON :

PHP

$response["message"] = “You have successfully submitted your email address.”;
$response["code"] = 1;
echo json_encode($response);

JS MOOTOOLS

new Request.JSON ({url: ‘…’,

onComplete: function(response) {

var code = response.code;
var message = response.message;

if(code) { //success!
// do success stuff
} else { //no good
// do error stuff, show detailed message
}

}
});

really easy !

Commenter Avatar August 20 / #

wouldn’t it be easier to have php return a json object? or perhaps a serialized Response class from PHP. I guess it depends on the complexity of the response and the information you need to retrieve from it.

Commenter Avatar August 20 / #

Like Bryan said, I’d make an array or stdClass object and json_encode it. That way you get something like this.

obj = { “code”: “1″, “message”: “You’re amazing!” }

Also, I don’t recall how well it worked, but I believe to get errors, I’ve thrown exceptions in PHP, and assigned it a proper error code, and handled it in the AJAX by checking for the response code.

David Walsh August 20 / #
david says:

@Bryan: Possibly. This, in my opinion, is just easier.

Commenter Avatar August 20 / #
Alan says:

http://us3.php.net/manual/en/function.json-encode.php

Use JSON encode function for PHP. The decode with Mootools to use as a javascript object. No need for extra unnecessary code.

David Walsh August 20 / #
david says:

@Alan: Good idea for servers that serve the specified PHP5, but in my shop, you can’t assume the hosting server will have PHP5. Thanks for the reference URL.

Commenter Avatar August 20 / #
Justin says:

David,

I used to do something very similar. For example, I’d send back a response that was pipe delimited to separate different sets of data. Then, each set of data was tilde delimited to separate functions to execute, variables, etc.

Then, I discovered JSON. It’s SO much easier. Now, I’m doing something very different. In my PHP, I write the JavaScript code that I want execute, return it to the calling page, and it gets executed.

I’m not sure this is smart or not, but it works VERY well. Since I’m primarily a PHP programmer, I prefer dealing with all the logic in PHP instead of trying to parse it out in JS.

David Walsh August 20 / #
david says:

I should say “we can’t assume” — you may assume away!

Commenter Avatar August 20 / #

Indeed I use JSON most of the time – simply encode it into a string (if I really need to), and decode on the other side. But for optimization sake – if we want to return a small amount of data – we might as well stick with a simple split().

Commenter Avatar August 21 / #
xrado says:

what about returning xml data, you can wrap any kind of data in to <![CDATA[$data]]>

David Walsh August 21 / #
david says:

@xrado: Interesting idea, but I feel my solution is a bit easier.

Commenter Avatar August 21 / #
thomasd says:

david says:

@Alan: Good idea for servers that
serve the specified PHP5, but in my
shop, you can’t assume the hosting
server will have PHP5.

I had the same problem and solved it with this sweet little class:

http://mike.teczno.com/JSON.tar.gz

The usage is as easy as:

require_once(‘JSON.php’);
$json = new Services_JSON();

//encoding an array or object
echo $json->decode(array(‘code’ => ‘0′, ‘message’ =>’Your email address is not valid. Please try again.’));

//same for decoding a string
$obj = $json->decode($json_string);

and if you not sure or don’t mind if your environment is php4 or php5 you can do something like this:

if(!function_exists(‘json_encode’)){
function json_encode($obj){
require_once(‘JSON.php’);
$json = new Services_JSON();
return $json->encode($obj);
}
}

if(!function_exists(‘json_decode’)){
function json_decode($str){
require_once(‘JSON.php’);
$json = new Services_JSON();
return $json->decode($str);
}
}

and you never need to worry about it again!

David Walsh August 21 / #
david says:

@Thomas: Awesome! Thank you for sharing that.

Commenter Avatar August 23 / #
Ahmed says:

Is this the same thing if I use JSON? Because if yes, it makes it way easier.

Commenter Avatar November 19 / #

Hi all, the solution is to use json_encode function in php, if you have a old version installed you may use the class json from http://www.boutell.com/scripts/jsonwrapper.html, it is a direct way to work. Some times i am having problem with the coding so may be you need to use utf8_encode() function for non standar characters.
I hope this help…
Regards , Enrique

Be Heard!

I want to hear what you have to say! Share your comments and questions below.

Name*:
Email*:
Website:  


© David Walsh 2007-2010. Contact David Walsh. Powered by the remarkable MooTools javascript framework.