jQuery: Preventing and then not preventing form submit using the "live" method
I am writing a form to be inserted in clients' webpages that is to be submitted with an AJAX request for processing. Then, depending on the client's settings, I want to either display a "Form Successfully Submitted" victory message, or I want to redirect the user to my site (by submitting the form to my site) for additional processing.
I'm using jQuery to try to get this to work. My strategy is to put a "live" binding to the submit event on my form, which then prevents the default submission and does a jQuery post using the form values as parameters for processing at my site. If the form passes validation AND its determined that the user needs to be redirected, the form submission is triggered again, but this time the submit handler returns true, which should enable the default, right? It does return true (I checked with alerts), but the form is not submitted. Here is sample code:
<form id="myform">
<!-- Elements in here -->
<input type="submit" value="Submit" name="submit" id="submit">
</form>
<script>
var handleSubmit = true;
$("#myform").live('submit', function(){
if (handleSubmit === true){
$.post('http://example.org', $('#myform').serialize(), function(response){
if (response.success){
if (response.redirect){
handleSubmit = false;
$('#myform').attr('action',response.redirect);
$('#myform').submit();
} else {
alert('success!');
}
} else开发者_JAVA百科 {
// replace form contents with response.html (the form w/ errors)
}
}, 'json');
return false;
} else {
// submit form (default action)
return true;
}
});
</script>
I've tried different things like putting the submit trigger within a setTimeout, or using 'bind' instead of using live, but the result is the same.
One thing that is perhaps important to note is that the above code and the code for the form itself is also generated from an AJAX request from the client's site.
Any guidance you could give would be much appreciated. I am also definitely open to different ways of doing this.
Thanks!
The problem that you're having is actually with the input element:
<input type="submit" value="Submit" name="submit" id="submit">
The redirecting form submit is failing because names of form controls within a form
element are exposed as properties of the form
in the DOM and can cause conflicts with the form
's original properties. Conflicts like this will fail silently when triggering events through jQuery's event functions. Changing your input
element to the following should fix the problem you're having:
<input type="submit" value="Submit">
精彩评论