Stack OverFlow
Stack OverFlow

Reputation: 61

Ajax: how to get post from its ID wordpress

I am new in ajax wordpress and I want to get post from its id, I am working this code, I am getting data but not filtered, it shows all the post titles in the popup.

add_action('wp_ajax_data_fetch', 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch', 'data_fetch');
function data_fetch(){
    //load more posts
    $post_id = $_POST["post_id"];

    $query = new WP_Query( array(
        'p' => $post_id,
        'post_type' => 'sponsors'
    ));

    if( $query->have_posts() ):
        while( $query->have_posts() ): 
            $query->the_post();
            the_title();

        endwhile;
    endif;

    wp_reset_postdata();

    die();
}

and here is my ajax code:

jQuery( document ).on( 'click', '#click_me', function() {
    var post_id = jQuery(this).data('id');
    jQuery.ajax({
        url : 'http://localhost/verturesort/wp-admin/admin-ajax.php',
        type : 'post',
        data : {
            post_id : post_id,
            action : 'data_fetch'
        },
        success : function( response ) {
            jQuery('#datainsert').append( response );
        }
    });
    return false;
});

and here is the LINK which i am using to get filtered data

<a href="#" name="post_id" data-post_id='<?php echo $postID; ?>' id="click_me" class="open_it" >Fetch Data</a>

Upvotes: 2

Views: 4216

Answers (2)

scraaappy
scraaappy

Reputation: 2886

Another approach is to use wordpress rest API to retrieve a post, native in wordpress. So your ajax call become:

jQuery( document ).on( 'click', '#click_me', function() {
    var post_id = jQuery(this).data('id');
    var request = jQuery.ajax({
        url : 'http://localhost/verturesort/wp-json/wp/v2/posts/'+post_id,
        method: "GET",
        dataType: "json"
    });

    request.done(function( data ) {
        console.log(data);
        jQuery('#datainsert').html(data[0].content.rendered);
    });

    request.fail(function( jqXHR, textStatus ) {
        console.log('fail')
    });
    return false;   
});

and you don't need the php part anymore

Upvotes: 1

Yassine Beloued
Yassine Beloued

Reputation: 65

Something is worng with your code :

// from your ajax call
var post_id = jQuery(this).data('id');
// from your html
<a href="#" name="post_id" data-post_id='<?php echo $postID; ?>' id="click_me" class="open_it" >Fetch Data</a>

To resolve do this :

<a href="#" name="post_id" data-id='<?php echo $postID; ?>' id="click_me" class="open_it" >Fetch Data</a>

Upvotes: 0

Related Questions