0

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;
            });
        });
    });
2
  • "i have multiple forms for each product in my page, but ajax working only for first form" -you've used '#form_add_to_cart' as a selector. That potentially only selects a single element with id=form_add_to_cart: ids ought to be unique on the page.
    – Rup
    Sep 23 at 11:42
  • Ok I change selector from ID to class, now click working, but still error 400
    – NCTI
    Sep 23 at 11:44
2

Your full form code does contain a hidden input named action with the value send_form.

However, you're not sending it correctly, because of the the contentType part in your JS script, which submits the form data as a JSON payload, but note that the old admin-ajax.php endpoint doesn't support JSON payload, hence $_REQUEST['action'] would be empty unless if you added it to the URL query string, and therefore WordPress won't know what the AJAX action is. So just remove the following from your JS code and the error would be gone:

contentType : 'application/json; charset=utf-8', // remove this

Additionally, your form doesn't have an input named send_form, so in your send_form() function, this will fail: if (isset($_POST['send_form'])). So you should add the input to your form or change the if condition.

Also, you should call wp_die() at the end in your function to exit the page and prevent WordPress from printing a 0 (zero).

6
  • Thank you that's working. Now i can't display passed data to my function. I run send_form(); on the same page when I Call ajax, and nothing display.
    – NCTI
    Sep 23 at 12:17
  • Your function as it stands now doesn't display any of the submitted data, but it would actually display either "ok" or "bad". And to retrieve the submitted data, just use the $_POST['input name'] format, e.g. $_POST['quantity']. Also, try var_dump( $_POST ); at the top in the function and you'd see a list of the submitted form data. But your original question has already been answered, so if you have another question, you can ask in another post. However, keep in mind, generic PHP questions are off-topic on this stack and should be asked on Stack Overflow instead.
    – Sally CJ
    Sep 23 at 13:05
  • Also, please undo your question's edit, i.e. roll back to the previous/original version. If you wanted to add new code, append it at the bottom and not modifying the part I told you to remove :)
    – Sally CJ
    Sep 23 at 13:09
  • It return me data like: array(2) { ["action"]=> string(9) "send_form" ["formData"]=> array(9) { [0]=> array(2) { ["name"]=> string(8) "quantity" ["value"]=> string(1) "1" } [1]=> array(2) { ["name"]=> string(7) "do_wash" ["value"]=> string(2) "on" } [2]=> array(2) { ["name"]=> string(10) "product_id" ["value"]=> string(2) "12" } [3]=> array(2) { ["name"]=> string(13) "product_price" ["value"]=> string(3) "0.5" } [4]=> array(2) { ["name"]=> string(26) "product_person_to_bringing" ["value"]=> string(1) "0" } [5]=> array(2) } } }
    – NCTI
    Sep 23 at 13:14
  • Now it return: array(2) { ["action"]=> string(9) "send_form" ["formData"]=> string(178) "quantity=1&do_wash=on&product_id=12&product_price=0.5&product_person_to_bringing=0&product_wash_price=0.2&product_bringing_price=0.4&product_calculate_bringing=0&action=send_form" } id_produktu0
    – NCTI
    Sep 23 at 13:18
2

In the data property you need to pass the action to be called with the rest of your data.
Based on you ajax action you action should be send_form

data: {
    action: 'send_form',
    formData: $("#form_add_to_cart").serialize()
}

Now in your php callback function you can do print_r($_POST) to see what the post request contains.

8
  • Unfortunately the same error.
    – NCTI
    Sep 23 at 11:35
  • @NCTI After the ajax request, can you go into network -> fetch/xhr -> find the request and check the response, what does it say? Sep 23 at 11:37
  • And i have multiple forms for each product in my page, but ajax working only for first form.
    – NCTI
    Sep 23 at 11:39
  • I see 0 in network -> fetch/xhr ->response
    – NCTI
    Sep 23 at 11:41
  • @NCTI seems like your url is incorrect, make sure you passed the correct url, if you are using url: 'https://domain.com/wp-admin/admin-ajax.php' im 100% sure it will not work, change it to your domain Sep 23 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.