phpajaxwordpressfrontendposting

Why AJAX posting Wordpress not works?


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);
    });
});

Solution

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