Trying out AJAX request for the first time and facing problem. I want to load a php file on button click in Wordpress site. So far after researching, I got this code:
index.php file:
<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>
ajax.php file (the file i want to be loaded):
<?php echo "Hello!" ?>
functions.php file:
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script('menu_toggle', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
// Grab php file output from server
ob_start();
include(get_template_directory_uri() . '/ajax.php');
$result['content'] = ob_get_contents();
wp_send_json($result);
}
menu_toggle.js file (js file with ajax code):
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
console.log(response);
alert(response);
$('#ajax').append("hello");
$('#ajax').load(response.content);
}
});
});
I can actually get alert(response);
which alerts[object Object], and $('#ajax').append("hello");
displaying, so that means that ajax was connected right way and ajax request is working correctly. But $('#ajax').load(response.content);
loading the same entire index page in #ajax div instead of loading the content of ajax.php file i actually want. I probably got the wrong code either in function tablo()
of functions.php file, or in ajax code of menu_toggle.js file. The console.log(response);
gives crazy amount of output. Can someone please help with this one?