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.

1
  • 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. Commented Apr 15, 2015 at 2:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.