我创建了一个插件,可以通过ajax提交表单。下面是php函数。
add_action(\'wp_ajax_nopriv_audience_intel\', \'audience_intel_ajax\');
add_action(\'wp_ajax_audience_intel\', \'audience_intel_ajax\');
function audience_intel_ajax() {
$likeit = $_POST[\'likeit\'];
$response = $_POST[\'response\'];
$postid = $_POST[\'postid\'];
add_option( \'testing_form_like\', $likeit );
add_option(\'testing_form_response\', $response);
global $wpdb;
$tablename = $wpdb->prefix . "intel";
$newdata = array(
\'radio\' => $likeit,
\'feedback\' => $response,
\'postid\' => $postid
);
$wpdb->insert (
$tablename,
$newdata
);
$result = "<p>Finished successfully!</p>";
// json_encode($result);
echo $result;
}
这是我的剧本。
jQuery(document).ready(function($) {
$(\'.audience_intel_container .close\').click(function(){
$(\'.audience_intel_container\').fadeOut(\'fast\', function(){
});
});
$(\'.audience_intel_container button\').click(function(){
console.log(\'clicked\');
var formdata = $(\'#audience_intel_form\').serialize();
$.ajax({
type : "post",
dataType : "html",
url : audience_intel_js.ajaxurl,
data : \'action=audience_intel&\'+formdata,
success: function(response) {
alert(response);
$(\'.audience_intel_container\').html(response);
}
})
})
});
表单数据已正确添加到数据库,但我无法在请求完成后显示输出消息。我在ajax函数中尝试了return、echo和echo json\\u编码。
我很欣赏你的见解。
SO网友:Eric Binnion
这是我正在使用的最后一个代码。感谢webaware指出我使用的数据类型不正确。
jQuery(document).ready(function($) {
$(\'.audience_intel_container .close\').click(function(){
$(\'.audience_intel_container\').fadeOut(\'fast\', function(){
});
});
$(\'.audience_intel_container button\').click(function(){
console.log(\'clicked\');
var formdata = $(\'#audience_intel_form\').serialize();
$.ajax({
type : "post",
dataType : "html",
url : audience_intel_js.ajaxurl,
data : \'action=audience_intel&\'+formdata,
success: function(response) {
alert(response);
$(\'.audience_intel_container\').html(response);
}
})
})
});
php
add_action(\'wp_ajax_nopriv_audience_intel\', \'audience_intel_ajax\');
add_action(\'wp_ajax_audience_intel\', \'audience_intel_ajax\');
function audience_intel_ajax() {
$likeit = $_POST[\'likeit\'];
$response = $_POST[\'response\'];
$postid = $_POST[\'postid\'];
add_option( \'testing_form_like\', $likeit );
add_option(\'testing_form_response\', $response);
global $wpdb;
$tablename = $wpdb->prefix . "intel";
$newdata = array(
\'radio\' => $likeit,
\'feedback\' => $response,
\'postid\' => $postid
);
$wpdb->insert (
$tablename,
$newdata
);
$result = "<p>Finished successfully!</p>";
// json_encode($result);
echo $result;
exit;
}