0

I have been using using PHP and pure Javascript for wordpress for a while, but I never manage to use AJAX. Currently I am trying to make an ajax call from one of my wordpress page by putting AJAX JS code directly into the page trying to call a PHP function from a file ajax.php (same dir with functions.php)

I have gone through many tutorial online regarding this part but no success. Even calling a simple PHP function just to echo "Hello World" doesn't work for me. I am positive that I don't need any "enqueue" for this part (since I am putting JS code in the page directly).

If someone can shed me some light on how can one make a very simple AJAX call using Javascript to activate a PHP function from the server (a very simple example would be really helpful), I would be much appreciated.

1

The WordPress Plugin Developer Handbook has background info and code samples of how to use Ajax in your plugin (and themes). Give it a read and it should get you on the right path.

0

Here's a very simple AJAX call on button click.

Note the standard wp_ajax_{action_name} only fires for logged-in users. If you need to also listen for Ajax requests that don't come from logged-in users, you need to use wp_ajax_nopriv_{action_name}

JS:

$('body').on('click', '.your-button', function(){
    var data = {
        'action': 'nam_nguyen_hook',
    };

    $.post(ajaxurl, data, function(response) {
        alert( response.message );
    }, 'json');
});

PHP:

add_action( 'wp_ajax_nam_nguyen_hook', 'nam_nguyen_hook' );
add_action( 'wp_ajax_nopriv_nam_nguyen_hook', 'nam_nguyen_hook' );

function nam_nguyen_hook() {
    $response = array();

    $response['status']  = 200;
    $response['message'] = 'Successfully sent an AJAX request';

    echo json_encode( $response );
    wp_die();
}

With this, if you have an element with class="your-button" in your admin, and click on it - you should get the "Successfully sent an AJAX request" message back.

Also note you need to make sure your ajax.php file is being required or included. Otherwise just put that PHP in your functions.php file.

  • So I went on a head and try this <script> jQuery(document).ready(function($) { jQuery("#export").click(function() { alert("clicked!"); var data = { 'action': 'export_excel' }; jQuery.post(ajaxurl, data, function(response) { alert( response.message ); }, 'json'); }); }); </script> <button id="export" class="button">Export All to Excel</button> while in functions.php, I just put the same thing with what you have for PHP, except changing 'nam_nguyen_hook' into 'export_excel', but I couldn't get anything back... – Nam Nguyễn Feb 27 '18 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.