I’m trying to send form data via AJAX to a php script that will create a new post in wordpress. The code I have seems like it should work, but for some reason nothing is happening.

The form is pretty huge, but the basic info I’m trying to get working now is:

<form action="/create-event" method="POST" enctype="multipart/form-data" class="event-form">
    <input type="hidden" name="userID" id="userID" value="<?php echo get_current_user_id(); ?>" />
    <fieldset>
        <label for="event-name">Event Name</label>
        <input type="text" id="event-name" name="event-name" value="" required />
    </fieldset> 
    <input type="text" id="event-main-cat" name="event-main-cat" class="main-cat" required />
    <input type="text" id="sub-cat" name="sub-cat" class="sub-category-input" value="" />
</form>

AJAX:

(function( $ ){
$( document ).ready(function() {
$('input[type=button]').on('click', function() {
    if( $('.event-form').valid() ) {
        var loadUrl = '/auto-save-post.php';
        // ajax the results!
        $.ajax({
            type: "POST",
            data: $('.event-form').serialize(),
            url: templateDir + loadUrl, // templateDir is declared in the footer
            success: function(result) {
                console.log('data sent!');
                console.log('sent to: ' + templateDir + loadUrl );
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }
        });
    }
});
});
})( jQuery );

PHP:

$data = $_POST['serialize'];
    // set basic event info
    $new_post = array(
        'post_type' => 'event',
        'post_author' => $data['userID'],
        'post_title' => $data['event-name'],
        'post_date' => Date('Y-m-d H:i:s'),
        'post_status' => 'draft',
        'tax_input' => array( 
            'main-cat' => $data['event-main-cat'],
            'sub-cat' => $data['sub-cat']
        )
    );
    // create the draft event
    $post_id = wp_insert_post($new_post);

Can anyone see where I’m going wrong?

Read more here: AJAX form to create new post (WordPress)


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , ,

Wordpress related questions and answers: