php - How to Load Ajax in Wordpress -
i'm familiar using ajax in ordinary way jquery.
i've played around while, don't understand wordpress needs work...
have here taken tutorial or article.
in functions.php (in child theme):
// code load jquery - working fine // code 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 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 loading , working fine.
i have tried basic ajax 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, don't know how can test see if it's loaded correctly begin with...
any here appreciated.
edit:
in firebug error:
referenceerror: ajax_script not defined url: ajax_script.ajaxurl,
as per request have put in answer you.
as hieu nguyen suggested in answer, can use ajaxurl javascript variable reference admin-ajax.php file. variable not declared on frontend. simple declare on front end, putting following in header.php of theme.
<script type="text/javascript"> var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; </script>
as described in wordpress ajax documentation, have 2 different hooks - wp_ajax_(action), , wp_ajax_nopriv_(action). difference between these is:
- wp_ajax_(action): fired if ajax call made inside admin panel.
- wp_ajax_nopriv_(action): fired if ajax call made front end of website.
everything else described in documentation linked above. happy coding!
p.s. here example should work. (i have not tested)
front end:
<script type="text/javascript"> jquery.ajax({ url: ajaxurl, data: { action: 'my_action_name' }, type: 'get' }); </script>
back end:
<?php function my_ajax_callback_function() { // implement ajax function here } add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' ); // if called admin panel add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' ); // if called front end ?>
update though old answer, seems keep getting thumbs people - great! think may of use people.
wordpress has function wp_localize_script. function takes array of data third parameter, intended translations, following:
var translation = { success: "success!", failure: "failure!", error: "error!", ... };
so loads object html head tag. can utilized in following way:
backend:
wp_localize_script( 'frontendajax', 'ajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
the advantage of method may used in both themes , plugins, not hard-coding ajax url variable theme.
on front end, url accessible via ajax.url
, rather ajaxurl
in previous examples.
Comments
Post a Comment