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 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问
  • ¥15 初学者如何快速上手学习stm32?