Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer Iron Ajax - How to access Response from Request after Error Event?

I use iron-ajax:

<iron-ajax
   id="postLoginForm"
   method="POST"
   verbose
   url="../../login"
   content-type="application/json"
   handle-as="json"
   on-response="_handleLoginResponse"
   on-error="_handleErrorResponse"></iron-ajax>

The server always responds with an error if the request body is empty:

Error: The request failed with status code: 422

This triggers my _handleErrorResponse method in which I would like to access the actual response, which looks like this:

{"email":["The email field is required."],"password":["The password field is required."]}

Here is what my _handleErrorResponse looks like:

_handleErrorResponse: function (event) {
  console.log(event);
  console.log(event.detail);
  console.log(event.detail.error);
  console.log(event.detail.error.message);
  console.log(event.detail.request);
  console.log(event.detail.response);
  console.log(event.detail.request.response);
},

And here is what the output looks like:

Developer Tools Output

So, how do I access the response so that I can output it to the view?

like image 796
LoveAndHappiness Avatar asked Feb 05 '16 09:02

LoveAndHappiness


People also ask

How do I get Ajax response time?

The most simple method would be to add var ajaxTime= new Date(). getTime(); before the Ajax call and in the done get the current time to calculate how long the Ajax call took to make. var ajaxTime= new Date(). getTime(); $.

Which is used to get response of an Ajax call as a string?

AJAX - Server Response The XMLHttpRequest object has an in-built XML parser. The responseXML property returns the server response as an XML DOM object.

What is function response in Ajax?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.

How do I send an Ajax request after some time?

Use setInterval() when you want to send AJAX request at a particular interval every time and don't want to depend on the previous request is completed or not. But if you want to execute the AJAX when the previous one is completed then use the setTimeout() function.


1 Answers

I think you can get the error JSON here:

event.detail.request.xhr.response

To get a more complete explanation, you can read the accepted answer to a different, but related question here:

Iron Ajax - How to access Response from on-response function?

Cheers!

like image 181
DaFi4 Avatar answered Sep 21 '22 16:09

DaFi4