admin ajax php 400 bad request
Ошибка 400 (Bad request) при работе виджета через AJAX
Возможно, тема уже избитая, но всё же.
Вроде всё делаю по документации, но почему-то всё равно получается ошибка 400. Где я ошибся?
P.S. Использую OpenServer. Виджет находится на сайте. Не в админке.
2 ответа 2
Вот полностью рабочий код (поместил его как файл в папку mu-plugins).
Короче, всё-таки разобрался сам.
Дело оказалось в том, что хуки wp_ajax_nopriv работают только если пользователь не залогинен. А, пытаюсь отправить запрос с сайта будучи залогинен. Поэтому ничего и не работало.
Чтобы AJAX запрос работал во всех случаях нужно ставить сразу два хука.
К сожалению, в документации об этом написано не совсем ясно. Но, тем не менее.
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php ajax wordpress или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.16.40224
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Getting 400 bad request error in Jquery Ajax POST
I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.
5 Answers 5
Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:
May be it will help someone else.
Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.
Bad Request. Your browser sent a request that this server could not understand.
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
The question is a bit old. but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
and pass them in your request
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
I needed to add the attributes to the controller:
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
WordPress.org
hi I’m trying to send with the POST method some data to a notification page.
I created a javascript file an ajax php handler page a the notification page.
here below you find the code I wrote in php for enqueuing the scripts etc.
the javascript function I’m using is:
Now here is the trouble I’ve seen many tutorials online
and they all use a new page to handle the ajax request, so i prepared a new page correctly included in the function.php.
inside this page I wrote this code:
and nothing happen not even an error it seems like that the xhr request doesn’t exists, so I moved the above mentioned code (the last part) in the notification page and here at least I get the 400 error bad request.
what am i doing wrong? any suggestion?
any help will be very appreciated thank you in advance.
I’m not sure if this is what you intended.
Anyway thank you again for you support.
bcworks, sorry to keep bothering you, but I’m not sure what you mean when you say I shell rearrange my code; do you mean in the javascript side? or in the php?
I rearranged the jQuery function following the indication of the link you posted, and in my opinion this should be the code:
is it correct?
do I still need to use the action hooks and the function?
because with this configuration I still have the 400 bad request error.
It’s not a bother, no worries.
Yeah, that JS script looks right. I did mean rearrange the JS script. Yes, you still need the PHP code as well.
BTW, your PHP Ajax handler needs to call die; when finished, otherwise the server waits to time out before sending a response.
I checked, and actually the ntfId wasn’t a string, but a number, strange because I’ve got it as an attribute (‘id’) of of a
Since on your installation the code works, I’m going to try now on a new WordPress installation and from there I’ll try to figure it out what’s wrong.
bcworkz thank you very much for your support.
There is any php or wordpress parameter to set in order to let ajax work?
I just installed a brand new wordpress website, with the default twentynineteen theme, on which I added three pages all in the theme root:
test-function.php
included it in the function.php (the standard twentynineteen function page) using:
page-test.php //as template
js-test.js // for javascrip
And I assigned to the sample page the test template.
the complete content of the test-function.php is:
the complete content of the page-test.php is:
and the complete content of the js-test.js is:
this is the ajaxurl:
I still get the same 400 bad request error.
WordPress is running locally on WAMP.
apache 2.4.37
php 7.2.14
mySql 5.7.24
Admin-ajax.php 400 (bad request) WordPress
How useful was this post?
Click on a star to rate it!
Share This Article
I’ve been working on ajax lately. The tutorials you find on the net are all very similar and relatively easy to implement. But I always get a bad request 400 on my ajax-admin.php
After a long and intensive search, I have now found out that’s because of the time of integration.
If I use the ‘init’-action-hook to initialize script and wp_localize_script, everything works fine. So the code itself must be correct.
But if I use, e.g.,’wp_enqeue_scripts’-action-hook, I always get a bad request.
The problem with this is:
I would like to have the functions in an extra PHP and only load them if needed on a particular page. For this, I need, for example, is_page(). But is_page() works at the earliest when I hook the function with the inclusion into the ‘parse_query’-action-hook:
So then in my-page-test-functions.php, ‘init’ does not work, I suppose because init comes before parse_query.
If you were thing about adding a Google search bar on your WordPress site, we’ve got you covered there as well.
Is there a best practice to organize this so it works? Or how can I fix the admin-ajax.php bad request when using the ‘wp_enqeue_scripts’-action-hook?
Hard to describe, but I hope it is pretty understandable.
That code registers your Ajax handler, but when you only run it on wp_enqueue_scripts, it’s already too late, and wp_ajax_nopriv_ hooks are already run.
Even after following all steps precisely, sometimes we do not get desired results. For example, not seeing a search box on the WordPress page could be possible for quite a few reasons.
Now, why didn’t your solution work?
The is_page() check meant that your functions file was only loaded on that specific page. ajax_login_init() gets called and your scripts enqueued. So far, so good.
Now your script makes the ajax call. As mentioned in the comments, ajax calls are not aware of the current page, you’re on. There’s a reason the file sits at wp-admin/admin-ajax.php. There’s no WP_Query, and thus is_page() does not work during an ajax request.
If you feel that your site and your audience require an Advanced search, you can read this post on how an advanced search form is helpful to find relevant search results. Additionally, WordPress advanced search form custom fields are a different subject and not for every website.
Since that does not work, sw18_page_specific_functions() won’t do anything in an ajax context. This means your functions file is not loaded, and your ajax handler does not exist.
That’s why you always need to include that functions file and move that is_page() check inside ajax_login_init()
You can skip to this article if the problem isn’t solved yet.




