1

I have this code in jQuery:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript" >
$(function() {
  $("input[type=submit]").click(function() {
    var name = $("#problem_name").val();
    var problem_blurb = $("#problem_blurb").val();

    var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;

    if(name=='' || problem_blurb == '') {
      $('.success').fadeOut(200).hide();
      $('.error').fadeOut(200).show();
    }
    else {
      $.ajax({
        type: "POST",
        url: "/problems/add_problem.php",
        data: dataString,
        success: function() {
          $('.success').fadeIn(200).show();
          $('.error').fadeOut(200).hide();

          // Here can update the right side of the screen with the newly entered information
          alert (dataString);
        }
      });
    }

    return false;
  });
});
</script>

And I have an AJAX call that I want to make JSON so I can unpack the JSON in the success case of the call to the AJAX.

What I don't understand is how to create the JSON and how to make the front end detect it, and how to unpack it and display it. Any advice with that?

My backend return will be simple. Just a name and description for every item returned.

Alex
  • 8,774
  • 1
  • 34
  • 42
Genadinik
  • 16,715
  • 59
  • 170
  • 277

2 Answers2

5

In add_problem.php use PHP's json_encode() on the object/array/scalar you want to return.

In your javascript, use jQuery's .getJSON() to make your AJAX call. Alternatively, you can use jQuery's .ajax() function and specify dataType: 'json'.

Here's documentation on jQuery's .getJSON():

http://api.jquery.com/jQuery.getJSON/

and here's some documentation on the PHP json_encode() function:

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

Jonathan M
  • 16,131
  • 8
  • 49
  • 88
  • Adding a header is a good idea too: header('Content-type: application/json'); – Brad Koch Sep 28 '11 at 18:36
  • @Jonathan In my php I have a result set variable I get from the database. Should I encode that? Or make it into an object first? – Genadinik Sep 28 '11 at 18:36
  • @Genadinik, definitely make the result set an object first, or else you get all the extra methods that go with the result set. Just make an object that contains the data only. – Jonathan M Sep 28 '11 at 18:38
  • 1
    @BradKoch, technically, yes, that's a good idea, but jQuery seems to handle it just fine without the header. Here's a good discussion on it: http://stackoverflow.com/questions/477816/the-right-json-content-type – Jonathan M Sep 28 '11 at 18:41
  • @Genadinik, it goes in the PHP code. Jonathan, Excellent link. I know it's not necessary, but it's just proper to send a correct MIME type. – Brad Koch Sep 28 '11 at 18:45
2

Make an array of what you want to return in php, preferably an associative array but it could be integer indexed and it will work just as well.

$arr = array();
// Fill array with return data with PHP.
$arr['name'] = 'John';

echo json_encode($arr);

That will render your array as output in JSON format, which your jQuery success function will pick up in a parameter. Below, I name the parameter json but you can name it whatever you like.

...
success: function(json) {
   var ob = $.parseJSON(json);
   // At this point, ob is a JavaScript object that should look pretty much the same 
   // as the PHP object you created.
   alert(ob.name); // In this example, will alert 'John'
}
...

Also note that $.parseJSON was not introduced in jQuery until version 1.4.1.

Please see: PHP Manual: json_encode()

Jeff Lambert
  • 23,036
  • 3
  • 61
  • 88
  • Thanks..1 question - how do I send the encoded json from the php to be in the json variable of the "success: function(json)" ? – Genadinik Sep 28 '11 at 18:41
  • That's the magic of jQuery's AJAX. Any output from your back end PHP script will appear as a string parameter passed to your success function. Since you are outputting JSON, I named the variable 'json'. – Jeff Lambert Sep 28 '11 at 18:43
  • by output do you mean I have to do something like echo $json; ....or whats the way to output the $json once its encoded? – Genadinik Sep 28 '11 at 18:45
  • The function `json_encode` will take an array and return a string containing that array in JavaScript Object Notation (JSON). The last line of my first code block takes that string and simply echos it out (making it _output_) – Jeff Lambert Sep 28 '11 at 18:47