Using Ajax in Wordpress for external script
Probably this is one of my biggest headaches. I have a project to deliver and i was using wordpress for development and speed.
After almost enjoying the good sail the big issue struck.
When i send data through AJAX to a PHP file that i wrote, the PHP get the message but my AJAX somehow keeps getting 404 response and when i check my console, its clear PHP replied.
Ok i did alot of tweaks and nothing worked and decided to search google which went for hours.
Lucky me i found the solution and i believe its important to share it here.
This is a post response by Tim Stone (a big thanks man) and i am not editing it but putting it up word for word.
When you include wp-blog-header.php
, you end up bootstrapping the whole WordPress setup routine. The function wp()
is called, which calls $wp->main()
, which in turn calls various setup functions.
One of these is $wp->query_posts()
, which calls $wp_the_query->query()
, which in turn calls WPQuery's ``` parsequery()function. I suspect that the 404 indication is generated in there (your AJAX page isn't a WP post, or anything like that), and is later transformed into an actual 404 response header by
$wp->handle404(), the function called after
queryposts()``` in main().
I'm not 100% sure that parse_query() is the definite culprit, but I would suggest seeing if you can just include wp-load.php instead, since I believe it does the actual work of creating the objects that you want to access.
Again, I don't actually use WordPress, so I can't be sure, but looking at the source code this seems to be the most likely case, from what I can tell.
Written by Oyewumi Abayomi
Related protips
2 Responses
check this https://coderwall.com/p/of7y2q
You have two ways to get around that:
- Include the correct file :) When you don't want to parse the request via WordPress' main query(like when handling AJAX via a php file), include the wp-load.php file
- Even better - send your AJAX to /wp-admin/admin-ajax.php with at least an "action" parameter.
Then in your plugin/theme you have to add(if your action parameter is "myaction")
add_action( 'wp_ajax_myaction', 'myaction_function_callback' );
Note that the above will only work for requests from logged-in users. To add support for non-logged-in users add this:
add_action( 'wp_ajax_nopriv_myaction', 'myaction_function_callback' );
myaction_function_callback should be an existing function(you can use any "callback" parameter - like array( $myobject, 'callback' ) ).
Once you're done with processing the AJAX request don't forget to do exit() or die() so that WordPress doesn't print '0' at the end of your output.