I’m trying to create an email signup form with an AJAX request.
Early on I found that WordPress empties the $_POST
variable by default. I tried using admin_post
and admin_post_nopriv
but neither of those seemed to be working. I’m now trying the following:
add_action('wp_ajax_nopriv_newsletter', 'subscribeToNewsletter');
add_action('wp_ajax_newsletter', 'subscribeToNewsletter');
function subscribeToNewsletter()
{
echo json_encode([ 'success' => true ]);
In my JavaScript, if I use the following:
axios
.post('/wp-admin/admin-ajax.php', {
'email' : 'abc@xyz.com',
'action' : 'newsletter',
})
.then(response => {
console.log(response.data);
});
I get a 400 bad request and a 0
returned. If I change it to:
axios
.get('/wp-admin/admin-ajax.php?email=abc@xyz.com&action=newsletter')
.then(response => {
console.log(response.data);
});
everything works.
Can admin-ajax.php
not handle POST
requests? I don’t want to use a GET
request* for subscribing someone to a newsletter, and I’d like to do it over AJAX.
*From W3 schools (which normally I hate but has a good overview on requests):
Some other notes on GET requests:
- GET requests can be cached
- GET requests remain in the browser history
- GET requests can be bookmarked
- GET requests should never be used when dealing with sensitive data
- GET requests have length restrictions
- GET requests is only used to request data (not modify)