我正在研究自定义的wordpress主题,我尝试使用ajax提交联系表单。我正确地完成了所有操作,并且数据正在插入数据库中,但是无法在html中打印成功消息,并且在控制台中也出现了错误,例如admin-ajax.php bad 400,但是当我单击它时,它显示了消息状态1。
<div class="container">
<h2 class="text-center"> Submit Your Query</h2>
<div class="text-center messageDiv" style="color:#fff">
</div>
<form action="" method="post" id="myform">
<!-- Form start -->
<div class="row">
<!-- Name -->
<div class="col-lg-4 col-12">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
</div>
<!-- Email -->
<div class="col-lg-4 col-12">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" required>
</div>
</div>
<!-- Phone -->
<div class="col-lg-4 col-12">
<div class="form-group">
<label>Phone</label>
<input type="text" name="phone" class="form-control">
</div>
</div>
<!-- Subject -->
<div class="col-lg-12 col-12">
<div class="form-group">
<label>Subject</label>
<input type="text" name="subject" class="form-control" required>
</div>
</div>
<!-- Message -->
<div class="col-lg-12 col-12">
<div class="form-group">
<label>Message</label>
<textarea class="form-control" rows="5" name="feedback" required></textarea>
</div>
</div>
<!-- Submit button -->
<div class="form-group mx-auto">
<button class="cutombtn-form" name="submit-form">SUBMIT</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
jQuery
<script>
jQuery(function(){
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery('#myform').submit(function(e){
e.preventDefault();
jQuery.ajax({
dataType: 'json',
type: "post",
data: jQuery("#myform").serialize(),
url: ajaxurl,
success:function(data){
jQuery('.messageDiv').html(data.message);
}
});
});
});
</script>
function.php
if(isset($_POST['name'])){
global $wpdb;
$data_array=array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
'subject' => $_POST['subject'],
'message' => $_POST['feedback']
);
$table_name= 'form_entry';
$row_result = $wpdb->insert($table_name, $data_array, $format=NULL);
//result of form
if($row_result == 1){
echo json_encode(array('message' => 'Form Submitted successfully','status' => 1)) ;
}
else{
echo json_encode(array('message' => 'Unable to submit the form.','status' => 0)) ;
}
}