questions

WordPress admin-ajax.php returns 0 and status 400 on POST, works on GET though

Rate this post

I have angular application embedded to WordPress site in iframe.

Angular app is trying to trigger WordPress action registered in the function.php file in the child-theme, code is as following:

angular_app.js

this.http.post('/wp-admin/admin-ajax.php', {action: 'my_sendmail', data: 'whatever'}).subscribe((response) => {
  console.log(response);
});

function.php

add_action( 'wp_ajax_my_sendmail', 'my_sendmail_function' );
add_action( 'wp_ajax_nopriv_my_sendmail', 'my_sendmail_function' );

function my_sendmail_function() {
    wp_send_json(array('resp' => 'Hello World!'));
    wp_die();
}

Above doesn’t work. Interestingly enough though, when I change JS code to:

this.http.get('/wp-admin/admin-ajax.php?action=my_sendmail').subscribe((response) => {
  console.log(response);
});

It works, however I do need to make it a POST as I need to post a quite a bit of data with the request. Anyone any idea what is going on here?

 

✔️Solution:

At the end I left attempt to get this working. I resolved it using a different available mechanism. In function.php I created new rest endpoint:

add_action( 'rest_api_init', function() {
    register_rest_route("as/api", "sendmail", array(
        'methods' => 'POST',
        'callback' => 'my_sendmail_function'
    ));
});

function my_sendmail_function() {
    ...email setup;
    wp_main($to, $subject, $body, $headers);
}

On the FE, in my Angular app:

this.http.post(location.origin + '/wp-json/as/api/sendmail', data).subscribe((response) => {
  console.log(response);
});

Works well.

Leave a Reply

Your email address will not be published.

Back to top button