Burhan Burhan - 1 month ago 10
Ajax Question

iron-ajax response returns null for php json response

I'm a beginner in polymer 1.0 in the following codes I'm trying to get json response from my php file when the iron-ajax's on-response triggers. I have tried different response by editing php, but it always shows null in my console log.
ajax part of the code


script part of code to handle on-response

postResponse: function(r){
console.log('Tip posted');
else{console.log('Error occured.not posted');}

I can't find any error but
returns null every time.

on my php I have.

$resp = '{"success":1}';
echo $resp;
echo json_encode($resp);

can't figure out which part I'm doing wrong. sorry for the possible dumb question.


You doing it all wrong in php. First of all json_encode will encode an array or an object to json string, it will escape your string, but thats not that what you want. Secondly you returning twice without [ ] bracket which cannot be parsed with JSON.parse or cannot be used as a JSON Object in javascript.

You should send back JSON content-type, because the response may be not hooked trough JSON.parse, and expecting a real JSON, but on the iron-ajax documentation the handle-as="json" means:

json: uses XHR.responseText parsed as JSON.

So the iron-ajax element using JSON.parse on the XHR.responseText to parse the JSON as an object, that means the PHP header is not required but you should use.

Change your php code something like this:


    $result = array('success' => 1);

    header('Content-Type: application/json');
    echo json_encode($result);