我有使用Ajax在WordPress上提交的表格。该表格可以正常工作,并且表格中的信息进入数据库并正确保存。
问题是我无法将其重定向到另一页。表格真的很简单
<form method="post" id="main">
<?php wp_nonce_field( 'my_nonce' ); ?>
<div class="columns is-multiline">
<div class="column is-4">
<input type="text" name="firstname" />
</div>
<div class="column is-4">
<input type="text" name="middlename" />
</div>
<div class="column is-4">
<input type="text" name="lastname" />
</div>
</div>
<div id="success_message"></div>
<div class="columns">
<div class="column is-3">
<input type="submit" name="submit-button" id="submit-button" value="Submit" />
</div>
</div>
</div>
</form>
然后我在functions.php
add_action('wp_enqueue_scripts', 'my_ajax_scripts');
function my_ajax_scripts(){
wp_localize_script( 'myscript', 'myajax', array( 'ajaxurl' => admin_url( '/admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'ajax_scripts');
function ajax_scripts(){
wp_enqueue_script( 'form', get_template_directory_uri().'/assets/js/form.js', array('jquery'), '1.0', true );
}
function form(){
global $wpdb;
if (!check_ajax_referer( 'my_nonce' )){
wp_die();
}
$table = UPC_jobs;
$formdata = $_POST['formdata'];
parse_str($formdata, $formdata_array);
$data = array(
'firstname' => $_POST['firstname'],
'middlename' => $_POST['middlename'],
'lastname' => $_POST['lastname'],
);
$format = array(
'%s', '%s', '%s',' %s'
);
$success=$wpdb->insert( $table, $data, $format );
if($success) {
wp_redirect( '/my-target' );
wp_die();
}
}
如果需要js部分
$('#main').submit(function(e) {
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
formdata.append("action", "form");
$.ajax({
type: 'POST',
url: myajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function( data ){
window.location.replace("https://example"); // this doesn't work as well
},
});
});
当我单击Submit
时,什么也没有发生,绝对没有。所有信息都按原样存储在数据库中,但是页面没有任何反应/显示任何内容。
可行的解决方案是仅显示一条消息,表明表单已成功提交(不是警报)
答案 0 :(得分:1)
您尝试使用始终代替成功的回调吗? 您可以尝试此方法
$.ajax({
type: 'POST',
url: myajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata
}).always(function() {
window.location.replace("https://example"); // this doesn't work as well
});