I have this element:
<template>
...
<iron-ajax
id="ajax"
url="..."
handle-as="json"
verbose=true
last-response={{ajaxResponse}}
loading="{{cargando}}"
on-response="_handleResponse">
</iron-ajax>
<div id="resultado"></div>
</template>
<script>
Polymer({
...
_handleResponse: function(event){
console.log("_handleResponse... ");
// this.$.resultado.innerHTML = event.detail.innerHTML;
}
});
</script>
The response I see in Firebug is:
<p>Hello word</p>
I want to access the response in _handleResponse function in order to set it as innerHTML of the resultado div, but nothing works.
I have tried:
event.detail.innerHTML
event.detail.response
event.detail.xhr.response
event.detail.xhr.responseText
event.detail.request.xhr.response (This route doesn't exist. How can it be the solution in Polymer Iron Ajax - How to access Response from Request after Error Event??)
If I debug and watch e.detail.response value when in on-response function:
In network tab I can see the response (simple 'hello'):
The response data is in fact returned in event.detail.response of the <iron-ajax>.response event. Your response field is null because you've misconfigured <iron-ajax>.handleAs. When you set it to json, the Accept-Type header is set to application/json and any response would be parsed with JSON.parse(). If your server ignores Accept-Type and sends whatever it wants, <iron-request> will attempt to parse the response as JSON and fail, causing a null response body per the spec. Note that hello and <p>Hello</p> are not valid JSON strings.
If you want to receive plaintext data, set <iron-ajax>.handleAs to text (the default is json).
Demo of <iron-ajax handle-as="text">
Demo of <iron-ajax handle-as="json">
event.detail.request.xhr.response (This route doesn't exist. How can it be the solution in Polymer Iron Ajax - How to access Response from Request after Error Event??)
The question you linked asks about the <iron-ajax>.error event, which has a different event detail than the <iron-ajax>.response event.
When <iron-ajax> receives a server response, it fires the response event with the corresponding <iron-request> as the event detail.
If the request fails for any reason, <iron-ajax> fires the error event with an object (containing the iron-request via the request attribute, and the underlying error via error) as the event detail.
Related
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;
}
I have the following situation:
I use ngResource to save some data to the mysql database and after the successfull save() I want to log the json response the server sends to me:
Document.save({}, postData, function(response){
console.log(response);
});
This does not result in a simple response, but in something like an object with its own methods. I want some smple output like the response.data after an $http.$get:
{
"docClass":"testets",
"colCount":1,
"columns":null,
"groupid":7,
"id":19,
"lang":"de",
"title":"test",
"version":1409849088,
"workflow":"12234"
}
Greets
Check out this answer
Promise on AngularJS resource save action
So I think in your case you need to do
var document = new Document(postData);
document.$save()
.then(function(res){});
But also from the link I provided
This may very well means that your call to $save would return empty reference. Also then is not available on Resource api before Angular 1.2 as resources are not promise based.
I am trying to make an http call to a URL to get a JSON and display this on my page.
The JSON looks like this:
{"ticker":{"high":484.01099,"low":470.37201,"avg":477.1915,"vol":2193393.03322,"vol_cur":4588.62668,"last":482.16,"buy":482.16,"sell":481.2,"updated":1398350394,"server_time":1398350394}}
The code is included below. I read that I have to use 'JSONP' to but I couldn't figure out how to use it.
<html ng-app>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.6/angular.min.js"></script>
<div id = "content" style="min-width: 1200px; max-width: 90%: margin-left: auto; margin-right: auto;">
<div style="width: 520px; float: left;">
<h4>Bot Summary:</h4>
</div>
<div ng-controller="TickerControl" style="width: 680px; float: left;">
<h4>Market Summary</h4>
<p>Price = {{data}} </p>
</div>
</div>
<div></div>
<script type="text/javascript">
function TickerControl($scope, $http, $templateCache) {
$scope.method = 'JSONP';
$scope.url = 'https://btc-e.com/api/2/btc_usd/ticker?callback=JSON_CALLBACK';
$scope.getTicker = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.getTicker();
}
</script>
</body>
</html>
UPDATE
I have now modified my code to try and do JSONP requests. I am getting the following error:
Resource interpreted as Script but transferred with MIME type text/html: "https://btc-e.com/api/2/btc_usd/ticker?callback=angular.callbacks._0". angular.js:8582
Uncaught SyntaxError: Unexpected token : ticker:1
I seem to be getting text back. Since I cannot control the server response, how can I parse this text to JSON... or just even display it... It's available to view in the chrome dev environment.
UPDATE 2
Apparently this seems to be an issue with the server not being configured properly. Since I don't have access to it, it would be nice to be able to just receive text and parse it in the client!
After doing some more research and experimenting with different methods, I regret to inform you that what you're trying to achieve cannot be done.
I sent a GET request to https://btc-e.com/api/2/btc_usd/ticker?callback=JSON_CALLBACK for testing purposes and in the response headers it says
content-type → text/html; charset=utf-8
Because you do cross domain calls and you have no access to the server, you have to use jsonp. But jsonp does not work with text/html content. This related to the error
Resource interpreted as Script but transferred with MIME type text/html
So even though the response looks like valid JSON, it is not treated as such by your client application.
To solve this you would have to add the proper Content-Type header on the server, but you have no access to it.
Quote from this related question:
jsonp can only be used if and when the server properly embed the response in a javascript function call.
To sum it up:
You should either
allow cross domain calls by configuring the server to do so
send back the proper content-type header by configuring the server to do so
Sadly you have no access to the server.
Be aware that this is not your fault. It is because the server is not configured properly.
If the response contains plain text you can parse it using "angular.fromJson(data)". Use a GET-request to fetch the data (and make sure the response does not actually contain HTML code).
I would like to set the userId and Password in JSON request header and remaining parameters in JSON request body. Can any give an example how can i set the userId/password in JSON request header and others parameter in JSON request Body.
Thanks in advance.
use Jquery:
<script>
//submit request
$.post('url',{userId: userIdvalue, Password: password value,...},function(response){
// do something when request processed successfully
});
//if you submit a form
$.post('url',{$("#formId".serialize())},function(response){
// do something when request processed successfully
});
</script>
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.