javascript - Submit Form via Axios to Wordpress
I have troubles with submitting a Form via Axios to Wordpress. Wordpress needs an "action" in the transmitted data and don't accept JSON as far as I know. So I created a URLSearchParams() object where I store my data, I want to send to wordpress. The Problem is, that I want to send an array of objects to wordpress via Axios, but I can't receive it in PHP.
var params = new URLSearchParams()
params.append('action', 'save_form')
params.append("x", x)
params.append("y", y)
persons.map((person, index) => {
params.append("myArr[]", JSON.stringify(myObj))
})
In PHP I want to receive the Objects like this, but because of URLSearchParams, the JSON is invalid...
foreach ($_POST["myArr"] as $myObjJson) {
// json_decode() fails
$myObj= json_decode($myObjJson);
}
How can I send the data from Javascript via Axios to my Wordpress-page and loop thru the array?
Answer
Solution:
Below is an example of sending using contact form 7.
var name = $('#nameField').val();
var email = $('#emailField').val();
const dataup = new FormData();
dataup.append("name", name);
dataup.append("email", email);
const response = axios
.post(
`https://yoursite.com/wp-json/contact-form-7/v1/contact-forms/{ID-FORM}/feedback`,
dataup
)
.then(function(response) {
// ... action
})
.catch(function(error) {
// ... action
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Source