[英]POST form on button click using jquery ajax
i'm trying to load form via ajax and submit form then write response to "#pagediv". 我正在尝试通过Ajax加载表单并提交表单,然后将响应写入“ #pagediv”。
Here is my working code 这是我的工作代码
$(function() {
$.ajax({
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
type: "GET",
data: { <?php echo $ajxparam; ?> },
dataType: "html",
cache: false
}).done(function( msg ) {
$("#pagediv").html(msg);
$("#savebtn").click(function(event){ event.preventDefault(); $("#testform").submit(); });
}).fail(function() {
$("#pagediv").html( "Request Failed. Please Try Again Later." );
});
});
modified code in form submit part(refer below); 表单提交部分中的修改代码(请参阅下文); its not working, did i missed anything?
它不起作用,我有什么错过吗?
$(function() {
$.ajax({
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
type: "GET",
data: { <?php echo $ajxparam; ?> },
dataType: "html",
cache: false
}).done(function( msg ) {
$("#pagediv").html(msg);
$("#savebtn").click(function(event){
event.preventDefault();
$("#testform").submit(function(evt) {
evt.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, $(this).serialize() );
posting.done(function( dte ) {
$("#successdiv").html(dte);
});
});
});
}).fail(function() {
$("#pagediv").html( "Request Failed. Please Try Again Later." );
});
});
Note:- Form POST URL is different from ajax load main page. 注意:-表单POST URL与ajax加载主页不同。
Inside your click event handler you're adding a submit event handler and not actually submitting the form. 在click事件处理程序中,您要添加一个Submit事件处理程序,而不是实际提交表单。 Since you're uploading the data via ajax on a button click just call the ajax in the button click callback.
由于您是通过按钮上的ajax上传数据的,因此只需在按钮click回调中调用ajax。
$("#savebtn").click(function(event){
event.preventDefault();
var $form = $("#testform"),
url = $form.attr( 'action' );
var posting = $.post( url, $form.serialize() );
posting.done(function( dte ) {
$("#successdiv").html(dte);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.