Sunday, September 16, 2012

wordpress ajax with different WordPress Address and Site Address

If in your WordPress General Settings WordPress address and Site address are different(if two domains are different), using Ajax in the frontend can be a little tricky. Usual approach is to localize a script :

        wp_localize_script('some_script_name, 'SomeVar', array(
                    'ajaxurl' => admin_url('admin-ajax.php')            
                ));

and you can get the ajaxurl from your javascript code by SomeVar.ajaxurl 

admin_url('admin-ajax.php') will return an url in respect to the Wordpress address. So, when you make an ajaxcall , it won't work, javascript will throw a cross-domain exception.


The solution is to use the home_url() and appending the ajax url:

        wp_localize_script('some_script_name, 'SomeVar', array(
                    'ajaxurl' => home_url('/').'/wp-admin/admin-ajax.php')           
                ));

and don't forget to add the nopriv hook:

add_action('wp_ajax_nopriv_action_name', 'function name');

other wise the frontend ajax won't work, as the request relays back to the WordPress url even if you're logged in as admin the request will not carry that info.


No comments:

Post a Comment

About Me

Web Developer From Dhaka, Bangladesh.