i'm trying to get the response from an iron-form in Polymer 1.
Form submit call a php script which return HTML code to insert in a div (ul and some li).
I use the iron-form event "iron-form-response" but i don't know how to get the response.
I can see the response in network tab of browser developer tools, but don't know how to get it in my element.
I don't find how to do in the iron-form documentation online.
Can someone help me please ?
What's happening, guys? All these responses confuse the OP when it is only this simple:
Your form:
<form is="iron-form" on-iron-form-response="responseHandler" action="http://localhost" id="myform">
<!-- Your form elements -->
</form>
Your script:
<script>
Polymer({
// Some scripts here.
// ...now your listener
responseHandler: function(e) {
console.log(e.detail.response);
},
});
</script>
It's just that. Nothing complicated. Don't over-complicate things.
Add Event Listeners to iron form.
ready: function(){
this.$.myform.addEventListener('iron-form-response',this.formResponse);
this.$.myform.addEventListener('iron-form-error',this.formError);
}
Form Response Function:
formResponse: function (e){
console.log("Server Response: ",e.detail);
}
Form Error Function:
formError: function (e){
console.log("Form Error: ",e.detail);
}
I'm going to build off of Talon's answer, which is correct.
e.detail will be a JSON object, assuming the response sent from the server is in JSON form. So, if you're using Node.JS and Express, you might have receiving code like this:
document.getElementById('my-form').addEventListener('iron-form-response', function (e) {
console.log('Form :', e.detail);
});
And your server code might look like this:
res.status(200).json({'foo': 'bar'});
After which e.detail will be the object {"foo": "bar"}
Small update.
I send some json with response:
res.contentType('json');
es.status(500).send({"foo":"bar"});
If I use 500 (error), I can reach the json data only by console.log(e.detail.request.xhr.response);
In case of code 200 it is reached by: console.log(e.detail.response);
Idon't get why it is so, but it's the only way for me((
<script>
Polymer({
is: 'rsvp-wedding',
attached: function() {
var form = document.querySelector('form');
form.addEventListener('iron-form-error', function(e) {
console.log(e.detail.request.status);
});
}
});
</script>
Related
Im using Woocommece in a WordPress website and some of the plugins installed make requests to an API to check and validate a vat field.
Id like to use .ajaxSuccess() to tap into the ajax response thats returned so I can check to see if part of it contains some data and do something on screen.
So far Ive got this.
jQuery(document).ready(function(){
var event = 'updated_checkout'
jQuery(document).ajaxSuccess(function(event){
console.log('success');
})
})
So the console spits out success. Great. But Im stuck as how I would move forward with this. I dont know how to get the XHR option or get he response in a variable.
Any help would be appreciated.
To get the response from the request in the $.ajaxSuccess() handler, retrieve the responseText property from the jqXHR object passed to the handler function in the second argument:
jQuery(document).ready(function($) {
var event = 'updated_checkout'
$(document).ajaxSuccess(function(e, xhr) {
console.log(xhr.responseText);
});
});
I am building a form using Polymer 1.0, using its iron-form element.
How can I get the error response body? The server is sending a JSON error back, and I can see it in the chrome inspector (network tab). But when my iron-form-error callback method is called, and I log it, the response JSON is nowhere to be found. I went through all the Object properties but nothing.
I also looked under event.detail.request.response but it is also null. Here is the code I'm using:
document.querySelector('#formPut').addEventListener('iron-form-error',function(e){
console.log(e);
// var json = $.parseJSON(e.detail.error.message);
});
Any help would be appreciated.
I eventually found my response body here...
e.detail.request.xhr.response
For those looking for the same thing under Polymer 1.0+, the status code can now be found under event.detail.request.xhr.status
_onError: function(event) {
statusCode = event.detail.request.xhr.status;
}
Here's my code:
<script type="text/javascript">
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username() {
$("#check_username").html('<img src="images/site/ajax-loader.gif" />username avilable??').delay(5000);
var usernametotest = $('#username').val();
$.post("backend/username_available.php", { username: usernametotest})
.done(function(data) {
$("#check_username").replaceWith(data);
});
}
</script>
I use this code for checking with AJACX the availability of a username in my form.
It works perfect but just once. When an username is occupied and I change the username, no AJAX checks are done after the first one? The text "username already exists" (in the variable data), is not replaced by "username ok".
This JavaScript is added just before the </html> tag.
Your code looks fine - see this jsfiddle with an alert on the usernametotest value for more visibility
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username(){
$("#check_username").html('username avilable??').delay(5000);
var usernametotest = $('#username').val();
alert('posting username ' + usernametotest);
$.post("backend/username_available.php", { username: usernametotest} )
.done(function(data) {
$("#check_username").replaceWith( data );
});
}
The post requests are being made every time with the correct payload, so no problems there (check browser developer tools e.g. Network tab / XHR in Chrome)
Must be an issue with the response coming back from backend/username_available.php? Check the response of the first request vs the rest, and the difference and hence the problem will probably jump out at you.
Whenever you replace an element... and here you do just that...
$("#check_username").replaceWith( data );
all those element's handlers are lost. So change() no longer works. To be able to use it again, you just need to bind again the element after it has been rewritten:
$('#username').change(check_username);
Or bind the handler to a parent and delegate it:
$('#username').parent().on('click', '#username', check_username);
(I feel that a class selector would work better - call it superstition on my part)
You could try this:
$('#username').on('change', function() {
// write your code here
});
I've created a form on a clients site and I'm trying to use AJAX for the subscribe form.
The submit seems to just redirect rather than serializing the form and working with AJAX.
I think the issue here is that it doesn't know whether the response data is "success" or not.. possibly utilises a different variable to determine if it was a success or error? It should display the message accordingly to the user either way, ie:
Success -> You have been signed up.
Error -> Invalid email address.
Should also be a message for a blank name entered as it's a required field but unsure how to handle that error.. :/
Complete Fiddle: http://jsfiddle.net/pUd5P/6/
Form
<form id="newsletter" action="http://app.bronto.com/public/webform/process/" method="post">
....
</form>
JS
//ajax subscribe
$( document ).ready( function() {
$("#newsletter").submit( function() {
//Do the AJAX post
//alert("submitting");
alert(data);
$.post($("#newsletter").attr("action"),
$("#newsletter").serialize(),
function( data ) {
//alert(data);
if ( data == 'success' ) {
$('#newsletter-message').html('You have been signed up.')
.removeClass('error')
.css('visibility','visible');
} else {
$('#field-error').html('Invalid email address.')
.addClass('error')
.css('visibility','visible');
}
});
//Stop the normal POST
return false;
});
});
have a look at event.preventDefault()
$("#newsletter").submit(function(event) {
event.preventDefault();
// rest of your code here.
This will prevent the form from submitting in the standard way and refreshing the page and allow your $.post to return results.
I can see you used return false but try this instead (or aswell as) :D
I just dont understand this behavior but make it work
http://jsfiddle.net/pUd5P/12/
it is creating the problem on name = sid so i just changed it to tsid
<input type="hidden" name="tsid" value="37ea72cebcc05140e157208f6435c81b" />
now its making an ajax request, You need to test it on your server as it is giving
Origin is not allowed by Access-Control-Allow-Origin. error.
So, I'm making a site that gets data from a server (Names, with an autocomplete script), gathers it all up, then on submit is SUPPOSED to send the data gathered to the server to get a JSON string back for usage further down on the page.
However, said server does not have the last part and I need to simulate it. But I have no idea how.
Using HTML, JS, jQuery and nothing else.
So the question being, as the structure is there,
how do I get
<form action="Search" method="get">
<input type="hidden" name="foo"/>
<input type="hidden" name="bar"/>
<input id="submitButton" type="submit" value="Search"/>
</form>
Where foo and bar will have values at the time of submit,
to end up as a JSON object containing foo, bar and some random data I just make up,
in the .js, on pressing submit, WITHOUT reloading the page. (That is, pressing submit just kicks in the script and gives the form data to it but nothing else)
Edit: Sorry, changed post to get. The server will when working, respond to GET with JSON.
Put whatever JS array/object you expect back from the server in returnedData:
$(function(){
var handleNewData = function(data){
alert('I got:\nfoo:'+data.foo+'\nbar:'+data.bar+'\nresults:'+data.results);
};
var reallySubmit = false;
$('form').submit(function(evt){
if (reallySubmit){
$.get(this.action,$(this).serialize(),handleNewData,'json');
}else{
// Put whatever spoof data you want here.
var returnedData = {
foo:this.elements.foo.value,
bar:this.elements.bar.value,
results:["jim", "jam", "jamboree"]
};
handleNewData( returnedData );
return evt.preventDefault();
}
});
});
See the working example here: http://jsfiddle.net/sQtkY/4/
Edit: Sorry, I forgot that jQuery will properly parse a JSON string for you if you pass the parameter. Updated the answer to show this; no need to stringify your spoof values.
Edit 2: OK, one more update to show you how to include form values as well as spoof data.
Try this:
$("form").submit(function (event) {
event.preventDefault();
// NOTE: the following would work when the server is ready
//$.getJSON("http://whatever.com/endpoint.php", $(this).serialize(), function(data) {
// console.log(data);
//});
var fakeData = {
whatever: "data",
you: "need",
foo: "value",
bar: "value"
};
console.log(fakeData);
});
Make sure you have firebug open to see the console.log().
Try this
$("form").submit(function(event){
event.preventDefault();
$.post("http://whatever.com/post.php",$(this).serialize(), function(data){
alert(data);
});
});