user13286
user13286

Reputation: 3075

React - WP_Mail works with jQuery but not axios

I have a contact form in my React app and I am attempting to have the form send an email using WP_Mail. I am trying to do that using Axios, but I can't seem to get it to work. I get a 400 error on the admin-ajax call.

axios.post(url, {
    action: 'send_form',
    data: {
        email: '[email protected]',
        message: 'testing'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function(error) {
    console.log(error);
});

I am able to get it to work using jQuery, but I'd rather not have to use that if possible:

$.ajax({
    url: url,
    dataType: 'json',
    data: {action: 'send_form', email: '[email protected]'},
    cache: false,
    success: function(data) {
        console.log(data);
    }.bind(this),
    error: function(xhr, status, err) {
        alert(err.toString());
    }.bind(this)
});

I think the issue has to do with the format of the payload header. When I use Axios, the data comes through as JSON payload header, but when I use jQuery it comes through as query string parameters.

Upvotes: 0

Views: 119

Answers (1)

Mohamed Magdy
Mohamed Magdy

Reputation: 605

Can you try:

let form_data = new FormData;
form_data.append('action', 'send_form');
form_data.append('email', '[email protected]');
form_data.append('message', 'testing');

axios.post(url, {
  form_data
})
.then(function (response) {
   console.log(response);
 })
 .catch(function(error) {
    console.log(error);
 });

Upvotes: 1

Related Questions