通过AJAX提交表格

我有一个表格如下:

Put in your email, and we send you instructions for changing your password.

我试图通过AJAX发布post,所以我做了一个简单的测试:

  $("#submitPasswordRequest").click(function() { var username = $('#passwordEmail').value(); console.log(username); /* $.ajax({ type: "POST", url: "/resetting/send-email", data: { username: username}, // serializes the form's elements. success: function( data ) { console.log(data); // show response from the php script. } }); */ return false; }); 

但是,似乎没有触发点击function,而是通过常规表单操作发布表单。 我在这做错了什么? 我想通过AJAX处理这个问题。

单击按钮时,只需将表单提交到后端即可。 要覆盖此行为,您应该覆盖表单上的submit操作。 老式:

  

新风格:

 $('form').submit(function() { return false; }); 

在提交时,您想要执行ajax查询:

 $('form').submit(function() { $.ajax({ }); // here we perform ajax query return false; // we don't want our form to be submitted }); 

使用jQuery的preventDefault()方法。 另外, value()应该是val()

 $("#submitPasswordRequest").click(function (e) { e.preventDefault(); var username = $('#passwordEmail').val(); ... }); 

完整代码: http : //jsfiddle.net/HXfwK/1/

您还可以收听表单的submit事件:

 $("form").submit(function (e) { e.preventDefault(); var username = $('#passwordEmail').val(); ... }); 

完整代码: http : //jsfiddle.net/HXfwK/2/

jquery和ajax

 $('form id goes here).submit(function(e){ e.preventDefault(); var assign_variable_name_to_field = $("#field_id").val(); ... if(assign_variable_name_to_field =="") { handle error here } (don't forget to handle errors also in the server side with php) after everyting is good then here comes ajax datastring = $("form_id").serialize(); $.ajax({ type:'post', url:'url_of_your_php_file' data: datastring, datatype:'json', ... success: function(msg){ if(msg.error==true) { show errors from server side without refreshing page alert(msg.message) //this will alert error message from php } else { show success message or redirect alert(msg.message); //this will alert success message from php } }) }); 

在php页面上

 $variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name ... then use server side validation if(!$variable) { $data['error']= true; $data['message'] = "this field is required...blah"; echo json_encode($data); } else { after everything is good do any crud or email sending and then $data['error'] = "false"; $data['message'] = "thank you ....blah"; echo json_encode($data); } 

您应该使用表单的submit处理程序而不是单击处理程序。 像这样:

 $("#formID").submit(function() { // ajax stuff here... return false; }); 

在HTML中,将ID formID添加到表单元素:

 

您需要阻止表单提交和刷新页面,然后运行您的AJAX代码:

 $('form').on('submit',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/resetting/send-email", data: $('form').serialize(), // serializes the form's elements. success: function( data ) { console.log(data); // show response from the php script. } }); return false; });