views:

96

answers:

4

I have a problem accessing JSON data. I'm new to JSON an jquery so there is probably a easy solution to it and i would be glad to find out.

My jQuery:

  $.post(
    "currentPage.php",
    { 
    'currentPage': 1
    },
    function(data){
      $("body").append(data);  
    }
  );

currentPage.php:

$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';

$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;

print json_encode($returnArray);

i tried to access the data like this: data.left data['left']

but it returns blank, how is the best way to access the data in the HTML-file?

A: 

http://php.net/manual/en/function.json-decode.php ??

tomaszsobczak
The php isn't the problem, i can append data and se the json but i can't get hold of the elemente within data
Cinaird
+1  A: 

In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.

$.ajax({
    url: "currentPage.php",
    data: { 
        'currentPage': 1
    },
    dataType: "json",
    type: "post",
    success: function(data) {
        $("body").append(data);  
    }
});
Andy
It is not quite true that there exists no shortcut, you can provide the datatype as parameter to `post()`
Felix Kling
@Felix thanks, updated
Andy
+1  A: 

Provide the datatype you expect to get as parameter to the .post() method (in your case json):

$.post("currentPage.php",{'currentPage': 1},
  function(data){
    $("body").append(data);  
  },
  'json'     // <-- add the expected datatype
);

I think the default is to treat the result as HTML. Read the documentation.

jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )

urlA string containing the URL to which the request is sent.

dataA map or string that is sent to the server with the request.

success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.

dataType The type of data expected from the server.

Felix Kling
+1  A: 

I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:

  $.post(
    "currentPage.php",
    { 
    'currentPage': 1
    },
    function(data){
      $("body").append(data);  
    },
    "json"
  );
Anthony