Just wanted to share a link that helps explain comments contained in the answer:
http://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/
Here's tip 1 mentioned in one of the comments:
- USE WP_LOCALIZE_SCRIPT() TO DECLARE JAVASCRIPT GLOBAL VARIABLES
Although wp_localize_script() is created for localization, it also has another great use. You can declare javascript variables with namespaces to use with your script. Here’s the syntax:
wp_localize_script( $handle, $namespace, $variable_array );
Here’s how you should declare the URL to the file that handles AJAX (in this example, I use admin-ajax.php, which is discussed in tip #2):
// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
This way, you won’t have to use PHP to print out JavaScript code, which is both ugly and non-cacheable. If you take a look at the generated HTML in the element, you’ll find this:
<script type="text/javascript" src="http://example.com/wordpress/wp-content/plugins/myajax/js/ajax.js"></script><script type="text/javascript">// <![CDATA[
<span class="mceItemHidden">
/*
*/
var <span class="hiddenSpellError" pre=""-->MyAjax = {
<span class="hiddenSpellError" pre="">ajaxurl</span>: "http://example.com/wordpress/wp-admin/admin-ajax.php"
};
/* ]]> */
</span>
// ]]></script>
Now, in your ajax.js file, you can use MyAjax.ajaxurl without having to resort to PHP and including wp-load.php. Please refer to tip #2 below for more about setting up the javascript code that sends the request, and how to handle the request properly.