views:

78

answers:

4

I have a script for updating a database table. I need to return a JSON array and to update some tables with JQUERY.

my php script:

$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);

jquery code:

$("button").live("click", function(event){
                    event.preventDefault();
                    $.getJSON("startsearch.php",{ searchId: $(this).val() }, function(data){
                        alert(data[0].status);
                    });

now ...the problem is that if i use $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) the script gets executed and i get a nice alert with value undefined. if i add the parameter "json" the script doesn't get executed anymore. I tried to use getJSON but again the same problem.

Anybody has any ideas? I am desperate...this has been bugging me for almost a week and I still haven't managed to solve it.

A: 

In your php file make sure to set the correct content type:

header("Content-type: application/json; charset=utf-8");

so that jquery can correctly eval the response into a json object.

Darin Dimitrov
`eval` is evil :) Use `json2.js` from http://json.org for more peace in mind ;)
Donny Kurnia
A: 

You can get to your response data as follows:

alert(data.status);
alert(data.results);
alert(data.totalResults);
Cryo
A: 

please don't use alert, install firebug into your firefox or enable the javascript console in chrome or safari. after that you can use console.log(data);

my guess is that data isn't an array. also have a look at the each() exmaple on the jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON

antpaw
A: 

Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.

I always write my AJAX request like this:

$.post(URL,
  { PARAM },
  function(data){
    try {
      var r = JSON.parse(data);
      //this for your code above
      alert (r.status); //should be 'COMPLETED'
    }
    catch (e) {
      //data is not in json format, or there are another exception in try block
      //do something about it
      alert('Exception occured, please check the data!');
    }
});

When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.

Donny Kurnia