Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I've prepared an array in php for ajax return with json_encode. When returned through ajax, it is not behaving as I expected.

ajax call and my attempt to interrogate results

$.ajax({

     url:"dbpaginate.php",
              type:"POST",
              data: {'environmentvars': tmp},
    cache: false,

    success: function(response){
        alert('Returned from ajax: ' + response);
        alert(response["actionfunction"]);
        $j.each(response, function (index,element) {
            alert(index);
            alert(element);


        });
});

first alert message:

Returned from ajax: array(5) {
["actionfunction"]=>
string(8) "showData"
["sortparam"]=>
string(6) "ticker"
["sortorder"]=>
string(3) "ASC"
["page"]=>
int(1)
["htmlstring"]=>
string(0) ""
}
{"actionfunction":"showData","sortparam":"ticker","sortorder":"ASC","page":1,"htmlstring":"","htmltext":"<table id=\"summaryheader\"> [...lots of html...]<\/div>\n"}

Second alert message

undefined

Expected result

showData

How can I effectively port my json response into a javascript object environmentvars? Thanks.

share|improve this question
    
In case someone else is stumped by the same, I was using a var_dump() in php to write to a server-side log, which added the initial text at the top. As I was new to ajax, I thought that the leading info in the first alert was part of a proper return. – deseosuho Apr 15 at 2:41

2 Answers 2

up vote 2 down vote accepted

You have to make the response valid JSON. It seems you have a print_r statement somewhere in your server side script, whose output gets included into the response. Remove that.

The response is always text, i.e. a string in JavaScript . You can parse the JSON before processing the data futher (Parse JSON in JavaScript?) or tell jQuery to parse it for you, by adding the dataType: 'json' option.

share|improve this answer

You should specify a dataType parameter in such methods which is basically used to declare the type of data you are expecting from the server.

Here is an example:

$.ajax({
  type: "POST",
  url: <your-request-url>,
  data: <your-data>,
  success: function(){ ... },
  dataType: "json"
});

More details here: https://api.jquery.com/jquery.post/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.