PolymerElements iron-ajax not posting data - polymer

This here is my iron-ajax element inside a dom-module:
This here is my javascript:
var iron_ajax = document.querySelector('iron-ajax');
iron_ajax.body = {"full_names":profile.getName(),"access_token":googleUser.getAuthResponse().id_token};
iron_ajax.generateRequest();
When I grab the $_POST variable and dump the contents to a file (after encoding them as json) I get []
(That means no data, zero, nothing). When I .log() the variables before sending them to ensure I'm not sending blanks, the values do appear, so it's not that I'm sending blanks.
I think it's a bug, or I just don't understand how it works. Can someone please help. Thanks.

I found a solution. This is not a Polymer problem. When you POST with content type JSON $_POST will not populate. Try this at server side:
$json = file_get_contents("php://input");
$_POST = json_decode($json, true);
Now your POST-Array will be filled with your request data.

I would like to know what is in your iron-ajax function, but here is what I have and it works.
<iron-ajax auto url="http://localhost:11111/api/Test" headers='{"Accept": "application/json"}' handle-as="json" on-response="ajaxResponse"></iron-ajax>
...
ajaxResponse: function (event) {
this.response = event.detail.response;
}

Related

JSON.parse returning undefined object

Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")

Polymer core-ajax won't post JSON?

I'm using core-ajax to retrieve JSON data just fine. Turning the component around to post back to the server as JSON is another thing altogether. In all cases, and irrespective of the contentType or handleAs parameters passed in, it appears that my JSON object I'm passing in as an input is being converted back to key=value in the server headers.
The code:
var ajax = document.querySelector('core-ajax');
ajax.method = 'POST';
ajax.handleAs = 'JSON';
ajax.contentType = 'application/json';
ajax.params = JSON.stringify(data);
ajax.go();
Really straightforward. The logs in Go give me:
2014/07/22 14:23:09 utils.go:139: OPTIONS /1/users/173?access_token=(token)
2014/07/22 14:23:09 utils.go:124: POST /1/users/173?access_token=(token)
2014/07/22 14:23:09 users.go:379: full_name=Greg%20Johnson
We've verified that there's no transformation happening on our side. Request headers are going out just fine.
I could completely be missing something. How else can we successfully POST out JSON data?
.params is for URL params. What you want is to post the JSON as the request body? For that, I believe you need to set the .body property:
This should do the trick:
ajax.body = data
See https://github.com/Polymer/core-ajax/blob/master/core-ajax.html#L151

extjs - How to submit a form when the response is not json?

I understand that when I submit a form, according to the documentation ExtJs by default parses the response as JSON.
In my case, the server returns HTML, that I want to display in a Panel. When I submit the from using getForm().submit(), ExtJs will throw an error about invalid JSON:
Ext.JSON.decode(): You're trying to decode an invalid JSON String
How can I tell ExtJs not to attempt to parse the response ? I could the access the text with the response object.
I don't know if you are looking for strictly an ExtJS framework solution. However, it seems you may be able to solve your issue possibly using xmlhttprequest directly since you are looking to push the html returned directly to dom?
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','/myPath/here',false);
xmlhttp.send();
var html = xmlhttp.responseText;
//assign value
In Ext.form.Basic configuration you can define your own reader and errorReader
Finally, it was impossible for me to get to work the form.submit() of ExtJs. I needed an implementation using Ext. And since this is a frequent pattern in my application, it is important to have a short an simple solution.
This is what I finally found (I have a modal window containing the form):
var values = me.up('form').getValues(),
panel = Ext.create('My.view.MyPanel', {
xtype: 'panel',
loader: {
url: Paths.ajax + 'sav_vpc/douane.php',
method: 'get',
params: values,
autoLoad: true
}
});
me.up('window').close()
This solution has another advantage over the me.up('form').getForm().submit() solution:
While .getForm().submit() is asynchronous, .getValues() is synchronous. Therefore, it is possible to close the window immediately.

Post JSON to Codeigniter controller

I am trying to receive and parse a JSON object sent in a POST request using Codeigniter but I cannot "find" it.
This is my controller code:
public function parse () {
$json = $this->input->post();
$json = stripslashes($json);
$json = json_decode($json);
print_r($json);
}
This is my JSON object:
{"data":"value"}
This is the correct way to do it.
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$post = json_decode($this->security->xss_clean($this->input->raw_input_stream));
When you use $this->input->raw_input_stream you can read it multiple times and its basically the same as file_get_contents('php://input'). This works on CI3. I don't know if it works on CI2.
Try this code, it will output an array with all your parameters.
$this->input->raw_input_stream;
$input_data = json_decode($this->input->raw_input_stream, true);
$input_data will return array
Try this instead
$json = $this->input->post('data');
$json = stripslashes($json);
$json = json_decode($json);
print_r($json);
You need to pass in the key of the data variable you want from the post array as an argument to post()
Firze's answer is correct but here is a more elaborated answer. I am not allowed to comment so I am posting it as an answer.
It has to do with CodeIgniter not being able to fetch JSON. jQuery does some under the hood tricks and transforms your data into form-data-x, that's why it works when you don't specify the content type, don't encode your object, or other situations.
If you want a pure JSON the solution is to use $this->input->raw_input_stream to fetch your JSON and decode it using php's json_decode. Check the full answer and code below:
Retrieve JSON POST data in CodeIgniter
controller:
puplic function exam(){
$obj = file_get_contents('php://input');
$edata = json_decode($obj);
echo $edata->name;
}
Go to post man->type->post
url:http://www.exam.com/exam
formate:json
{
"name":"atm fahim"
}
==>send
make sure you have POST data, using $this->input->post() it will always return empty, you should put on the input type name $this->input->post('name_of_input_text')
Are you sure you're POSTing the data and not doing a GET instead? I ran into this issue earlier today (which is how I found this question) and I was doing a POST but using JSONP which seems to be done with a GET.
CodeIgniter has a function called get_post that will get the data from wherever it happens to be.
$this->input->get_post_string('data');
I hope this helps you out.
You can do it manually like so if you'd like.
function get_post($index = '', $xss_clean = FALSE){
if ( ! isset($_POST[$index]) )
{
return $this->get($index, $xss_clean);
}
else
{
return $this->post($index, $xss_clean);
}
}
I know this is an old post, but for others looking, this might be helpful:
On the browser side, I create my data packet using code similar to this pattern:
var form_data = { };
$.each($('#mvt_dialog_form').serializeArray(), function() {
form_data[this.name] = this.value;
});
// add the address data to the payload
var result = {
form_data: form_data,
locations: addressData,
selected_location: selectedLocation
};
// now wrap it all up with a pretty bow
// Seriously, the key:value format is required for codeigniter INPUT class to be able to "see"
var movement = {
movement_dlg: JSON.stringify(result)
};
I then "post" movement to the server.
In the controller, I then use the following logic:
// Perform XSS filtering
$postData = $this->input->post(NULL, TRUE);
$result = json_decode($postData['movement_dlg']);
Just add correct content type to your request header
Content-Type: application/json
In order to use the standard CI methods.
In index.php, insert a couple of lines:
$json = json_decode(trim(file_get_contents('php://input')), true);
if(!empty($json)) {
$_POST = $json;
}
Either implement in the bootstrap.
RIP Codigniter...(
try
json_decode(array($this->input->post()))
OR
$tmp[] = (array)json_decode($this->input->post());
print_r($tmp);

Update two different values with one AJAX response

I want to update two different values with one ajax-response.
<span id="nr1">Change this</span>
<span id="nr2">and change this</span>
Now I can just change one value, I do like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText;
Is it possible to do something like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText1;
document.getElementById('nr2').innerHTML = xmlHttp.responseText2;
**** UPDATE ****
The response comes from php.
I'm totally new to JSON.
There are no responseText1 and responseText2 properties of an XMLHTTPRequest(which I assume your xmlHttp is), just responseText, so you have to return something parsable in that responseText field(like JSON). So you server may send back {"firstResponse":"value1","secondResponse":"value2"} and you can fill your fields from that JSON string. Use the json2.js library from json.org
<script type="text/javascript" src="json2.js"></script>
. . .
var theResponse = JSON.parse(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = theResponse.firstResponse;
document.getElementById('nr2').innerHTML = theResponse.secondResponse;
EDIT:
In order to craft this JSON response from PHP you should use the PHP JSON libraries. There are several examples in the json_encode page that can get you started. The other code I posted(and that is posted in other responses) are all browser side javascript code.
$arr = array ('firstResponse'=>'value1','secondResponse'=>'value2');
echo json_encode($arr);
Place that code into your PHP script to generate the JSON string
{"firstResponse":"value1","secondResponse":"value2"}
Then the previously posted javascript code will parse that.
If you trust and control the server, just return a dictionary in JSON for the response and use it on the client side. So:
v = eval(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = v['nr1']
document.getElementById('nr2').innerHTML = v['nr2']
As already said it would make sense to return your Ajax call as a JSON Object. I recommend the more secure JSONP call (don't know if you can use any library that supports this natively).
// Your script returns this
callback123(
{
"nr1" : "This is conten for nr1",
"nr2" : "Some content for nr2"
});
// JavaScript callback looks like this
function callback123(data)
{
for(var key in data)
document.getElementById(key).innerHTML = data[key];
}
use JSON.parse
link text