This morning I spent a little time constructing an ajax call from a front-end page (not an admin page) using wp_ajax. As is my wont, I tested this in Firefox and all was well. I used the WP codex.
Then I tried it in Opera and it failed, no response whatsoever, just a 0 in the ajax response. Seemed odd that Opera should have a problem, tried it in Chrome, same thing. Lots of Googling later, saw loads of similar questions being asked, no answers…
I then looked at the code in wp_ajax, and all became clear…
I had entries in my functions.php
as follows:
add_action('wp_ajax_myfunction', 'myfunction');
function myfunction() {
//stuff
}
So if I pass an action of ‘myfunction’ to wp_ajax it should call the hook at the top of the above code, which in turn calls myfunction(), right? Only if you are logged on to WordPress at the time! If you aren’t logged in, wp_ajax calls the hook wp_ajax_nopriv_myfunction
. And that’s why it worked for me in Firefox, because I was also logged on through Firefox. Nowhere is this mentioned in the codex, that I can see.
Having identified this it’s then simple to add another hook to your functions.php
:
add_action('wp_ajax_nopriv_myfunction', 'myfunction');
Hope this saves someone an hour or so…
Tags: wordpress
Thank you!
Thank You man. Saved me hours.
Impossible to guess what might be the problem. Since this is largely server side code browser variations are not likely. Start with IE dev tools. look for any errors there. Just possible there might be a js error somewhere else on the page that’s preventing the ajax call I suppose.
I have same type of problem. but it is working all browser without IE. Can you please help me?
Saved me an hour or ten. Thanks!
Thank you, Simon! It really helped me a lot!
More information on the subject can be found here:
http://codex.wordpress.org/AJAX_in_Plugins
I was curious as changing the callback functions name never triggered an error. This really helped otherwise a long days work.
Thanks! 🙂
Thank you so much!!!! that is wondefull. I would not have guessed that one. I don’t know why WP doens’t provide this information in the documentation. It solved my problem as well.
Absolute legend. Saved me a lot of messing around. Thanks!
Thank you very much……man!!!!
I trying to solve this front ajax response probelm……from about some
hour….
BY using this function my problem has been solved!!!!!
Thanks “””Dude””” Again!!!!!
Thanks for the reminder! Ha. You saved me some time on this one.
Thank you so much!
You save me a lot of time 😀
Oh, man, thank you so much! I was getting desperate already.
Thanks man, this helps a lot!
This worked for me. Adding _nopriv_ is what was missing in my ajax call. Thank you.
Thank You! it works 🙂
My God, thank you so much. I was nearly postal.
Thank you! Thank you!
Oh man – this post certainly saved me some time. I thought it was because some crazy client was using IE!
Much appreciated.