Ajax in WordPress – path issue

I am trying out a bit of Ajax ( via jQuery ) in WordPresss. I have everything working correctly but for some reason I have to have the full URL to the PHP handler file even though it’s located in the same directory as the script.

Here’s the code:

$.post('http://full/url/to/file.php', $("#form").serialize(), function(data){
  do stuff
  ...
}); 

Why cant I just put “file.php” into that? Why does it need the full URL? Or more importantly, what can I put in there that would work on any site without the end user having to put in the full URL every time?

P.S. I have read the problem with Ajax and the path to the PHP page but I just got a bit more mixed up. I have also read the Ajax in plugins page on the WordPress codex but I couldn’t see a relevant example in there. I suspect this might have something to do with wp_localise_script() but I’m not sure.

1 Answer
1

it needs a full URL because even though it may be the right location relatively on the back end, it’s not on the same on the front end, at the URL where your page is ultimately served.

you’re on the right path with wp_localize_script. you want to enqueue your ajax script, then pass the admin ajax url to wp_localize_script:

function my_init_method(){
    wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/my_ajax_script.js', array( 'jquery' ) );
    wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('init', 'my_init_method');

now within your ajax script you can refer to MyAjax.ajaxurl for the URL.

Check this post for a great writeup on properly using ajax in plugins and themes, this is what the WP Codex links to as an example.

Leave a Comment