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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line