AL-zami
AL-zami

Reputation: 9066

access elements of an ajax response comes as a stirng of array

i have requested to my server for list of posts submitted by users .But in response i get a string containing array of stdClass object.If it was actual array it wouldn't be a problem.But it comes as a sting.Like the following:

   " array(
      [0]=>stdClass('title'='title of post','post_id'=4),
      [1]=>stdClass('title'='title of post','post_id'=4)
    )"

typeof(response) is giving me "string".My question is , how i can get access to individual elements from this ? code:

$.ajax('../includes/ajaxpostinfo.php',{
    data:data,
    type:"POST",
    success:function(response){

        alert(typeof(response)); // it prints out "string"


        },
    error:function(response){
          alert(response);
       }
});

Upvotes: 2

Views: 225

Answers (2)

Anand Singh
Anand Singh

Reputation: 2363

Do some thing like this:

Server:

$array= array(
      [0]=>stdClass('title'='title of post','post_id'=4),
      [1]=>stdClass('title'='title of post','post_id'=4)
    );
echo json_encode($array);

Client:

$.ajax('../includes/ajaxpostinfo.php',{
    data:data,
    type:"POST",
    dataType : "json",//set data type
    success:function(response){

        alert(typeof(response)); 


        },
    error:function(response){
          alert(response);
       }
});

Upvotes: 4

Esta
Esta

Reputation: 81

Maybe if you add

dataType : "json"

in your ajax request

"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

JQuery Ajax documentation

Upvotes: -1

Related Questions