我已經關注了一些關於Wordpress如何與Ajax交互的教程,並且我試圖爲我的用戶構建一個前端表單。我的HTML開始:使用AJAX序列化數據並在Wordpress中調用動作
<form id="myform" action="" method="post" enctype="multipart/form-data">
<div id="apf-response" style="background-color:#E6E6FA"></div>
<input type="text" name="title" id="title" value="titlevalue">
<input type="text" name="description" id="description" value="descvalue">
//other inputs
<input type="submit" class="submit" value="Publish"/>
</form>
我已經註冊並localizd我的腳本
我創建wp_ajax_priv和wp_ajax_nopriv功能,如:
function apf_addpost() {
get_currentuserinfo();
$uid = $current_user->ID;
$results = '';
$project_title = $_POST['title'];
$project_description = $_POST['description'];
$pid = wp_insert_post(array(
'post_title' => $project_title,
'post_content' => $project_description,
'post_status' => 'publish',
'post_author' => $uid,
'post_type' => 'project',
));
if ($pid != 0)
{
$results = '*Post Added';
}
else {
$results = '*Error occurred while adding the post';
}
// Return the String
die($results);
}
add_action('wp_ajax_nopriv_apf_addpost', 'apf_addpost');
add_action('wp_ajax_apf_addpost', 'apf_addpost');
,我已經writtend這非常簡單的ajax功能,其中不起作用:
$(document).ready(function(){
msform_init(); //validation function which I'm not showing but it's working
$('#myform').submit(function(event){
event.preventDefault();
apfaddpost(); // which is my below ajax function
})
})
function apfaddpost() {
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
action: 'apf_addpost', //where I should send data and trigger the php
data: $('#myform').serialize(),
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
很明顯,我錯了,但我看不到錯誤。我想我正在序列化數據並調用非常糟糕的操作,但我不知道如何解決它。你可以看到我不是專家。提前致謝。
這太好了!謝謝!事情是,我有很多輸入,所以我想序列化它們,所以我已經修復,經過多次這樣的嘗試 – XiLab