JQuery: Preventing and then not preventing form submission using the live method

I am writing a form that needs to be pasted into the web pages of clients that must be submitted with an AJAX request for processing. Then, depending on the client’s settings, I want to either display a victory message “The form was sent successfully” or I want to redirect the user to my site (by sending the form to my site) for additional processing.

I am 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 makes a jQuery message using the form values ​​as parameters for processing on my site. If the form passes the test and determines that the user should be redirected, the form submission starts again, but this time the submit handler returns true, which should include the default value, right? It returns true (I checked with warnings), but the form is not submitted. Here is a 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 { // replace form contents with response.html (the form w/ errors) } }, 'json'); return false; } else { // submit form (default action) return true; } }); </script> 

I tried different things, for example, to put a send trigger in setTimeout or use "bind" instead of using live, but the result is the same.

Perhaps it is important to note that the above code and the code of the form itself are also generated from an AJAX request from the client’s site.

Any guidance you could give would be greatly appreciated. I am also definitely open to different ways of doing this.

Thanks!

+4
source share
1 answer

The problem you are facing is actually related to the input element:

<input type="submit" value="Submit" name="submit" id="submit">

Submitting the redirect form fails because the names of the form controls inside the form element are displayed as form properties in the DOM and may cause conflicts with the original form properties. Conflicts like this fail when triggering events through jQuery event functions. Changing the input element to the following should fix the problem you are facing:

<input type="submit" value="Submit">

+1
source

All Articles