I try tu run wp form with ajax but console return
Wordpress admin-ajax.php 400 bad request.
jQuery(function ($) {
$(document).ready(function () {
jQuery('#form_add_to_cart').on('submit', function () {
jQuery.ajax({
url: 'https://domain.com/wp-admin/admin-ajax.php',
method: 'post',
contentType : 'application/json; charset=utf-8',
data: $("#form_add_to_cart").serializeArray(),
success: function (response) {
alert(response);
},
fail: function (err) {
alert("There was an error: " + err);
}
});
return false;
});
});
});
here is my functions.php file:
add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users
add_action('wp_ajax_nopriv_send_form', 'send_form'); // This is for unauthenticated users.
function send_form(){
if (isset($_POST['send_form'])){
echo'ok';
}
else{
echo 'bad';
}
}
and my form:
<form name="form_add_to_cart" method="POST" class="form_product" id="form_add_to_cart" action="">
<input hidden="hidden" name="action" id="add_product_to_cart"
value="send_form">
<input class="btn btn-primary" type="submit"
name="add_to_cart-<?php echo $product_id; ?>" id="add_to_cart"
value="Dodaj">
all form : https://pastebin.com/YJXTjGjJ
WORKING:
jQuery(function ($) {
$(document).ready(function () {
jQuery('#form_add_to_cart').on('submit', function () {
jQuery.ajax({
url: 'https://domain.com/wp-admin/admin-ajax.php',
method: 'post',
data: $("#form_add_to_cart").serializeArray(),
success: function (response) {
alert(response);
},
fail: function (err) {
alert("There was an error: " + err);
}
});
return false;
});
});
});