0

I'm building a custom post type plugin using a class. I've got a form on a page which makes an AJAX call, and this returns a 400 Bad Request and a 0 response.

I've tried making the call independently of the page using Postman. Still the same response.

In constructor:

add_shortcode('websites_form', [$this, 'renderForm']);

// handle AJAX calls for both logged in and guest users
add_action('wp_action_websites_cpt_create_post', [$this, 'create_post']);
add_action('wp_action_nopriv_websites_cpt_create_post', [$this, 'create_post']);

The other two methods:

public function renderForm() {

    wp_register_script('websites-cpt-process-form', plugins_url('js/process-form.js', __FILE__), null, null, true );

    // vars being sent to JS
    $php_vars = [
        // passing the url to call for passing the form data back to WP
        'ajaxurl' => admin_url( 'admin-ajax.php', isset( $_SERVER["HTTPS"] ) ? 'https://' : 'http://' )
    ];
    wp_localize_script( 'websites-cpt-process-form', 'phpvars', $php_vars );

    wp_enqueue_script( 'websites-cpt-process-form' );


    return file_get_contents( plugin_dir_path( __FILE__ ) . "partials/websites-form.php" );
}

public function create_post() {
    global $oLog;

    $oLog->logrow('POST', $_POST);

    // verify nonce

    // create post with name in title

    // add url in metadata

    // echo response
    echo json_encode($_POST);

    // die
    die();
}

So it looks like the wp_action-XXX actions aren't getting registered. I tried putting echo's and such in the create_post() method, but nothing showed up in the output.

Any suggestions appreciated. I'm not sure where to turn to next.

  • 1
    Do you instantiate the class? It's hard to tell without seeing the whole code. – Jack Johansson Mar 11 '18 at 1:37
  • 1
    Oh yeah, sure. I understand. Always worth asking obvious questions. You never know. @Sally figured it out: I was hooking wp_action_XXX instead of wp_ajax_XXX. d'Oh! – NotoriousWebmaster Mar 11 '18 at 1:59
2

I believe the problem is here:

// handle AJAX calls for both logged in and guest users
add_action('wp_action_websites_cpt_create_post', [$this, 'create_post']);
add_action('wp_action_nopriv_websites_cpt_create_post', [$this, 'create_post']);

Because the format should be:

add_action( 'wp_ajax_{ACTION_NAME}', [ $this, 'create_post' ] );
add_action( 'wp_ajax_nopriv_{ACTION_NAME}', [ $this, 'create_post' ] );

..where {ACTION_NAME} is the "action" name, e.g. websites_cpt_create_post.

See wp_ajax_{$_REQUEST['action']} and wp_ajax_nopriv_{$_REQUEST['action']}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.