Reputation: 23
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
<iron-ajax
id="ajax"
method="POST"
url="post_tip.php"
handle-as="json"
on-response="postResponse"
>
</iron-ajax>
script part of code to handle on-response
postResponse: function(r){
console.log(r.detail.response);
if(r.detail.response.success==1){
console.log('Tip posted');
}
else{console.log('Error occured.not posted');}
}
I can't find any error but r.detail.response
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.
Upvotes: 1
Views: 397
Reputation: 604
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:
<?php
$result = array('success' => 1);
header('Content-Type: application/json');
echo json_encode($result);
Upvotes: 1