Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Return Multiple Values From AJAX Using MooTools and PHP

18 Responses »

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?

Discussion

  1. dr.death
    August 20, 2008 @ 8:06 am

    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();

  2. thomasd
    August 20, 2008 @ 8:27 am

    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? :)

  3. nacho
    August 20, 2008 @ 10:11 am

    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 !

  4. August 20, 2008 @ 10:56 am

    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.

  5. August 20, 2008 @ 12:01 pm

    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.

  6. August 20, 2008 @ 12:59 pm

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

  7. alan
    August 20, 2008 @ 3:54 pm

    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.

  8. August 20, 2008 @ 4:51 pm

    @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.

  9. justin
    August 20, 2008 @ 4:52 pm

    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.

  10. August 20, 2008 @ 4:56 pm

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

  11. August 20, 2008 @ 5:41 pm

    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().

  12. August 21, 2008 @ 8:01 am

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

  13. August 21, 2008 @ 8:32 am

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

  14. thomasd
    August 21, 2008 @ 8:52 am

    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!

  15. August 21, 2008 @ 10:58 am

    @Thomas: Awesome! Thank you for sharing that.

  16. August 23, 2008 @ 1:47 pm

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

  17. November 19, 2009 @ 2:26 pm

    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!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!