I'm familiar with using ajax in the ordinary way with jQuery.
I've played around it for a while, but don't understand what Wordpress needs to get it to work...
What I have here is taken from some tutorial or article.
This is in functions.php (in a child theme):
// code to load jquery - working fine
// code to load javascript file - working fine
// ENABLE AJAX :
function add_ajax()
{
wp_localize_script(
'function',
'ajax_script',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
$dirName = get_stylesheet_directory(); // use this to get child theme dir
require_once ($dirName."/ajax.php");
add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php
add_action('template_redirect', 'add_ajax');
The jQuery itself is loading and working fine.
I have tried some basic ajax like the following:
jQuery(document).ready(function($){
$('a.link').click(function(){
$.ajax({
url: ajax_script.ajaxurl,
data: ({action : 'function1'}),
success: function(data){
$('#result').html(data);
}
});
return false;
});
});
Besides this, I don't know how I can test to see if it's even loaded correctly to begin with...
Any help here would be appreciated.
EDIT:
In firebug this error:
ReferenceError: ajax_script is not defined
url: ajax_script.ajaxurl,
As per your request I have put this in an answer for you.
As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.
As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:
Everything else is described in the documentation linked above. Happy coding!
P.S. Here is an example that should work. (I have not tested)
Front end:
Back end:
UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.
WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:
So this simply loads an object into the HTML head tag. This can be utilized in the following way:
Backend:
The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.
On the front end, the URL is now accessible via
ajax.url
, rather than simplyajaxurl
in the previous examples.