Wordpress: execute do_shortcode() inside ajax func

2019-02-28 19:43发布

问题:

I'm implementing a wordpress frontend php page which holds a list of hyperlinks in the body and a wpdatatable in the footer.

I want to reload the data table each time the user selects a link and this needs to be done through ajax without reloading the whole page.

What i did so far:
I defined my action in \wp-content\themes\Avada\functions.php as the following:

function tenders_shortcode() {
    echo do_shortcode("[wpdatatable id=49 var1=".$_POST['id']." var2=".$GLOBALS['cgv']['archive']."]");
}

add_action('wp_ajax_tenders_shortcode', 'tenders_shortcode'); // add action for logged users
add_action( 'wp_ajax_nopriv_tenders_shortcode', 'tenders_shortcode' ); // add action for unlogged users

And inside my home page i made the ajax call as the following:

function toggleTable(ministryId) {


    $.post( '<?php echo admin_url('admin-ajax.php'); ?>', {    
      action: "tenders_shortcode",
      id: ministryId
    }, function(datatable) {
      alert("success");
      jQuery("#tendersResult").html(datatable)
    });

}

where "tendersResult" is a div which should hold the datatable.

The problem is that the html of the returned data table holds css link tags and it always display "0".

Following is how it's displayed in the browser, see the 0 text:

And this is how it's displayed in the inspector:

Please note that i've done a lot of research before posting my question and nothing fixes my problem. Any help is appreciated !!

Update: Okay, so i've added wp_die() as suggested by Fencer04, but my problem now is that do_shortcode() still returns "" css tags in the header and the datatable is returned as "display:none"

回答1:

You need to change your function to:

function tenders_shortcode() {
    echo do_shortcode("[wpdatatable id=49 var1=".$_POST['id']." var2=".$GLOBALS['cgv']['archive']."]");
    wp_die(); //Added
}

add_action('wp_ajax_tenders_shortcode', 'tenders_shortcode'); // add action for logged users
add_action( 'wp_ajax_nopriv_tenders_shortcode', 'tenders_shortcode' ); // add action for unlogged users

Without wp_die() at the end of the function it will never return anything other than zero.



标签: php wordpress