Horia
Horia

Reputation: 2982

wordpress ajax call using jquery

I need to make an ajax call from every page of my wordpress website.

In order to do this I added the following in my functions.php file located in my child theme

// Enqueue your JS file
function my_enqueue($hook) {    
    wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri() . '/js/my-script.js', array('jquery') );

    // in JavaScript, object properties are accessed as ajax_object.ajax_url
    wp_localize_script( 'ajax-script', 'My_Ajax_bject',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' )
    ));
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );


// AJAX request handler
function my_action() {
    global $wpdb;  // you can use global WP variables and so on
    $whatever = intval( $_POST['whatever'] );
    $whatever += 10;
    echo $whatever;
    
    $time = date( "F jS Y, H:i", time()+25200 );
    $ban = "#$time\r\n$whatever\r\n"; 
    $file = get_stylesheet_directory_uri() . '/errors.txt'; 
    $open = fopen( $file, "a" ); 
    $write = fputs( $open, $ban ); 
    fclose( $open );
    
    wp_die();
}
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

This is my js file placed in my child theme folder in /js/my-script.js file

jQuery(document).ready(function($) {
    var data = {
        'action': 'my_action',
        'whatever': 1
    };

    $.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

I have also tried this js snippet, but still no luck

(function($) {
$(document).ready(function() {
var data = {
        'action': 'my_action',
        'whatever': 1
    };

    $.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
})
})(jQuery);

Unfortunately I do no see the errors.txt file created.

I created the file manually but I do not see anything in it.

Please advise.

Thank you

Upvotes: 0

Views: 512

Answers (1)

Howard E
Howard E

Reputation: 5639

There's an error in your localize script:

The second parameter in localize_script should be the name you're using in your js file.

// Enqueue your JS file
function my_enqueue($hook) {    
    wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri() . '/js/my-script.js', array('jquery') );

    // in JavaScript, object properties are accessed as ajax_object.ajax_url
    wp_localize_script( 'ajax-script', 'ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' )
    ));
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );

Upvotes: 1

Related Questions