javascriptphpjqueryjson.post

JSON with jQuery and PHP


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.


Solution

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