Ajax Submit Page Refresh
I've been going nuts, and I can't seem to figure how to stop the page from refreshing when submitting a form via ajax.
I've set up a jsfiddle for you to look at: this link
I've done the event.prefentDefault() and return false; but can't seem to get it working. Am I just being stupid?
The end result should be that when 开发者_开发知识库the form is submitted, the form area should dissappear and be replaced by the "hidden" ajax_message which simple reads: "check your phone".
Thanks in advance for saving my hairline :)
You submit_number
function is defined inside the "document ready" event handler and is visible only inside that function (scope) and its children, so you can't use it from HTML, where only the global scope is available.
If you would have firebug or something similar activated you would see just that in the error console.
A quick hack to make it work would be to replace
function submit_number(event) {
with
window.submit_number = function(event) {
thus explicitly putting your function in the global scope, but it is not the recommended way. There's no point in polluting the global scope with your single purpose function.
A better approach would be to register your function as an event handler from JS like so:
$('form.kinkast_signup').submit(submit_number);
Also you may want to add an ID to that form and reference it by ID instead of class name.
I fixed your fiddle:
http://jsfiddle.net/ntJux/5/
I just assigned the event handler unobtrusively, as in:
$('#idOfTheForm').submit(function(event){
...
});
Instead of using an "onclick" in your form, bind it to your JavaScript.
So, instead of
function submit_number(event)
do
$(form).submit(function(event)
<form method="post" class="kinkast_signup" onsubmit="submit_number(); return false">
<input id="login_email" type="text" name="to" />
<input id="signInButtonSubmit" type="submit" name="action" value="Send" />
</form>
And then
window.submit_number=function() {
//Prevent Default page refresh on submit
//event.preventDefault();
......
}
preventDefault() can be removed.
Function that is called when onclick event happens should simply return false.
Try this http://jsfiddle.net/ntJux/6/
Check these out:
http://hasin.wordpress.com/2009/10/01/jqueryhooking-form-submit-and-making-it-an-ajax-request/
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/
精彩评论