doulao3078 2014-09-13 16:43
浏览 62
已采纳

为什么AJAX发布Wordpress不起作用?

I'm trying to posting post via ajax at Front End, but I'm always failed.

What I'm doing wrong? here is my code it returns me 0:

HTML

<form id="add" name="add" method="post" enctype="multipart/form-data">
    <label for="title">Title</label>
    <input id="title" type="text" name="post_title" value="">
    <input type="hidden" name="action" value="my_action">
    <input id="submit" value="Submit" type="submit">
</form>

PHP

wp_enqueue_script( 'my-ajax-request', '/js/my_js.js' );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'MyAjax.action' => 'my_action', 'MyAjax.post_title' => $_POST['post_title'] ) );

add_action('wp_ajax_nopriv_my_action', 'addpost_ajax_handler' );
add_action('wp_ajax_my_action', 'addpost_ajax_handler' );
function addpost_ajax_handler() {

echo 'reached ajax handler'; // delete this line later

if( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
    $title = $_POST['post_title'];
    $my_post = array(
        'post_title' => $title
    );
    $result = wp_insert_post( $my_post );
    if ( ! is_wp_error( $result ) ) echo 'success';
}
die();
}

my_js.js

$('#submit').on('click', function(e) {
e.preventDefault();
var data = { 'action': MyAjax.action, 'post_title': MyAjax.post_title };
    $.post(MyAjax.ajaxurl, data, function(response) {
        alert(response);
    });
});
  • 写回答

3条回答 默认 最新

  • doucang6739 2014-09-14 17:25
    关注

    thanks to all, problem solved. I needed to put the code of php handler in functions.php, instead a custom page)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件
  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗
  • ¥20 双非跨考工科哪个专业和方向就业前景好?
  • ¥20 求会6sv辐射传输模型,辅导(可py6s🙏🏻有偿
  • ¥15 .xla后缀的文件拖到excel里什么内容也没有怎么办
  • ¥20 Workbench中Mechanical打不开、闪退是什么原因?
  • ¥240 MapReduce应用实践 学生课程