0

I need to show the various content of a post in a modal overlay.

How do I call Wordpress through AJAX from the front end (directly from a .js file), using the classic jQuery method?

$.ajax({
    'url' : ?
    data : {
        'id' : 247 <-- post ID
    }
    ...
});

This is NOT a PHP file, so no:

admin_url('admin-ajax.php?action=my_action&post_id='.$post->ID.'&nonce='.$nonce);

Or?

0

You can output your javascript via wp_add_inline_script(). This way you can set the post's id and AJAX URL before outputting the code:

wp_add_inline_script('my-js', '
    jQuery.ajax({
        \'url\' : '.admin_url('admin-ajax.php?action=my_action').'
        data : {
            \'id\' : '.get_the_ID().'
        }
    });');

Note that you need to hook to an existing js file to be able to add inline script, so my-js must be a valid enqueued script.

| improve this answer | |
1

Add this in your functions.php file:

function my_action() {
    $the_post_id = $_POST['id'];

    $output = json_encode( get_post( $the_post_id ) );
    header('Content-Type: application/json');
    echo $output;
    wp_die();
}
add_action('wp_ajax_my_action',        'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

Enqueue the scripts:

function add_scripts() {
    wp_enqueue_script( 'app', get_template_directory_uri() . '/assets/js/build.min.js', array(), '1.0.0', true );

    wp_localize_script( 'app', 'my_ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'add_scripts' );

The AJAX call from your js file:

$.ajax({
    url : my_ajax_object.ajaxurl,
    type: 'POST',
    data : {
        'action' : 'my_action',
        'id' : 214 // And whatever else you need to pass on ...
    }
}).done(function ( response ) {

}).fail(function ( err ) {

});
| improve this answer | |

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.