php – WordPress POST AJAX call, var_dump($_POST) NULL and AJAX response empty when inside ob_start
when i click on a tab, i want it to return a specific type of posts,
here’s the code html one of the tabs:
<ul id="menu-menu-secondaire-blog" class="nav nav-tabs">
<li class="nav-item"">
<a id="test" href="#articles" class="nav-link tabs-link border-white active" role="tab" data-toggle="tab">Tous les articles</a>
</li>
so i chose to use AJAX to get the href of the clicked tab and send it to my front,
here’s the function in my file functions.php where i want to send my ajax response :
function js_scripts (){
wp_enqueue_script( 'cool-stuff',get_stylesheet_directory_uri() . '/js/script.js', array('jquery'), false, false);
wp_localize_script( 'cool-stuff', 'ajaxurl', admin_url( 'admin-ajax.php' ) );}
add_action( 'wp_enqueue_scripts', 'js_scripts');
add_action( 'wp_ajax_get_attr_href', 'get_attr_href');
add_action( 'wp_ajax_nopriv_get_attr_href', 'get_attr_href');
function get_attr_href() {
var_dump($_POST);
ob_start();
include 'articlesTabs.php';
return ob_get_clean();
}
add_shortcode('shortcode-articles', 'get_attr_href');
and here’s my jQuery code in my scripts.js:
Query(document).ready(function($) {
// ---------------------------------------------------------------------------------------
$('a[data-toggle="tab"]').on('shown.bs.tab', function (event) {
console.log($(this).attr('href'));
var href = $(this).attr('href');
var newData = {
"action": "get_attr_href",
"href_post": href
};
$.ajax({
url: ajaxurl,
type: 'POST',
data: newData,
success: function (response) {
console.log('success');
}
});
});
});
when i click on the tab, i go to Inspect->Network and i get this response:
with success in my console,
i have two problems:
1 – if you look at my function get_attr_href(), i have var_dump($_POST) and it returns empty : var(), and it should return the $_POST array that containes the values returned by the AJAX call.
2 – if i put the $_POST inside the ob_start it no longer returns a response either.
what i can do in this situation?
Thanks in advance !
Leave an answer