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条)

报告相同问题?