[php] How to Load Ajax in Wordpress

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,

This question is related to php jquery ajax wordpress

The answer is


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.

<script type="text/javascript">
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

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:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.

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:

<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 from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front 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:

var translation = {
    success: "Success!",
    failure: "Failure!",
    error: "Error!",
    ...
};

So this simply loads an object into the HTML head tag. This can be utilized in the following way:

Backend:

wp_localize_script( 'FrontEndAjax', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
) );

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 simply ajaxurl in the previous examples.


I'm not allowed to comment, so regarding Shane's answer, keep in mind that

wp_localize_scripts()

must be hooked to wp or admin enqueue scripts. So a good example would be as follows:

function local() {

    wp_localize_script( 'js-file-handle', 'ajax', array(
        'url' => admin_url( 'admin-ajax.php' )
    ) );

}

add_action('admin_enqueue_scripts', 'local');
add_action('wp_enqueue_scripts', 'local');`

Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

1.in my htaccess file that lives in my wp-content folder i add this below what's already there

<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>

In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

2.) In my ajax code i can then use my url like this

$.ajax({
    url:'/wp-content/themes/themeName/forms.php',
    data:({
        someVar: someValue
    }),
    type: 'POST'
});

obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.


Use wp_localize_script and pass url there:

wp_localize_script( some_handle, 'admin_url', array('ajax_url' => admin_url( 'admin-ajax.php' ) ) );

then inside js, you can call it by

admin_url.ajax_url 

Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins

Secondly, ajax_script is not defined so you should change to: url: ajaxurl. I don't see your function1() in the above code but you might already define it in other file.

And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r() or var_dump() will be your friends.


I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.

Hopefully will help someone else.

Here is the corrected code from the question:

// code to load jquery - working fine

// code to load javascript file - working fine

// ENABLE AJAX :
function add_ajax()
{
    wp_enqueue_script(
       'function',
       'http://host/blog/wp-content/themes/theme/js.js',
       array( 'jquery' ),
       '1.0',
       1
   );

   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');  

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to wordpress

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ How to get WooCommerce order details Wordpress plugin install: Could not create directory WooCommerce: Finding the products in database How to get post slug from post in WordPress? How to get featured image of a product in woocommerce Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610 Use .htaccess to redirect HTTP to HTTPs Load More Posts Ajax Button in WordPress How to decode encrypted wordpress admin password?