0

I am developing a WP plugin. I have two same AJAX calls, one is working, and second one is giving me 400 Bad Request error for admin-ajax.php.

ReadyState is 4, responseText is: " ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵ ↵0", statusText is "Bad Request", error is POST http://localhost/wc_addtocart_as_admin/wp-admin/admin-ajax.php 400 (Bad Request)

Both calls are getting data from two separated <form> elements. When I change data in working AJAX to use array defined in js code, like in example below, it gives me the same error like the second AJAX call which is not working at all.

    var test = [];
            test[0] = {name: "reason", value: 'OLALA'};
            test[1] = {name: "second", value: 'TRUS'};

    jQuery.ajax({
                url: test_ajax_object.ajax_url,
                type: 'POST',
                data: test

                etc...

                })

So, only first AJAX works with first <form> data. And second one, which is absolutely the same, doesn't.

What could be possible reasons for this weird behavior? Please let me know if I should provide some more info.

Headers difference

1 Answer 1

0

They're not the same though. Look at the form data on each one. The second one, the one that doesn't work, has _test appended to the parameter names and the action value.

The reason you're getting a 400 error is because you're not sending a valid action. The action parameter is how WordPress determines which callback to use to handle the request. If you don't send action with a valid value, no callback exists to handle the request and it returns a 400 error.

You need to make sure the parameter is called action, not action_test, and the value is the proper name you're using in PHP. In your case that appears to be return_reason, not return_reason_test.

1
  • 1
    I assumed and key names and values in associative array I am sending through AJAX are arbitrary. But on my second thought, yes, I am aware that action value must equal to wp_ajax_{name}, and that form must have it's "action", but somehow I forgot that. Probably because I was too tired. Thanks for your answer.
    – Tahi Reu
    Nov 12, 2018 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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