Php Not Receiving Post Body Set In Polymer Core-ajax Element
Solution 1:
in this case you would want to use the "params" attribute this.$.login.params = '{"foo": 1, "bar": 2}';
in place of the "body" attribute. doing so would allow you to get the data with $_POST. the following plunker i used for another answer showing how i create a form in polymer but will also work here to show sending $_POST data to a backend with php. http://plnkr.co/edit/JG7KKbMK0R1Fa1W2Gb4P?p=preview
Solution 2:
Here is how I'm using core-ajax to POST some data:
in the template:
<core-ajax
method="POST"id="core_ajax_el"
on-core-response="{{ajax_get_responseHandler}}"
>
</core-ajax>
in the prototype:
domReady: function(e) {
//set AJAX request params: they will be POSTed to the ajax-url.var core_ajax_el = this.$.core_ajax_el;
// create the object literalvar aniArgs = {};
aniArgs['post_data'] = this.element_attribute;
core_ajax_el.params = aniArgs;
//set the AJAX URL
core_ajax_el.url = this.ajax_get_url;
//execute AJAX
core_ajax_el.go();
},
ajax_get_responseHandler: function(e, detail, sender) {
//do something with the response here
}
Solution 3:
So I did some research and made some important findings.
core-ajax has a property contentType which is by default set to 'application/x-www-form-urlencoded'.
The data I was sending was a json object, and it was not url-encoded.
PHP populates $_POST and $_REQUEST when it contains url-encoded data. Further, the data must be in the form of key=value[&key=value...] pairs, as with GET query variables, for the PHP assoc array indices to be instantiated.
So I could have sent the data with the following code:
this.$.login.body = 'data='+encodeURIComponent(JSON.stringify({"foo":1, "bar":2}));
now in the PHP script:
echo$_POST['data']; // outputs something like string(32) "{\"foo\":1, \"bar\":2}"var$unescaped = stripslashes($_POST['data']);
echo$unescaped; // outputs string(29) "{"foo":1, "bar":2}"$assoc_array = json_decode($unescaped, true); // now contains an assoc array of the// json data
However, I've seen people use the following code in their PHP script:
file_get_contents("php://input");
This gets raw POST data sent to the web server, regardless of whether or not it is url-encoded.
So, I can just as easily continue sending the data with:
this.$.login.body = '{"foo": 1, "bar": 2}';
and with PHP have the data set using:
$data = json_decode( file_get_contents( "php://input", true ) );
echo$data["foo"]; // outputs 1
Post a Comment for "Php Not Receiving Post Body Set In Polymer Core-ajax Element"