1

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.

deseosuho
  • 958
  • 3
  • 10
  • 28
  • 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 '15 at 02:41

2 Answers2

2

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

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/