Include PHP file via AJAX call

I’m trying to call a .php file located within a subfolder of my plugin via an ajax request. I’ve tried lots of different ways of including, including get_template_part, but I just can’t seem to get the content to render. I feel like I’m probably doing this wrong, but I’m not sure what to try next. The file is located one directory above and then into another directory called “Templates”.

tps_show_modal is a custom function, the 2nd argument is the content of the modal box. (this function is confirmed working elsewhere).

Any help is appreciated.

PS. I also need to pass a variable (spaceID) to the included file, hence the use of set_query_var().

Here’s my ajax request:

$(document).on(‘click’, ‘.uiSpaceTitle’, function(e) {
var spaceID = $(this).attr(‘data-spaceid’);
$.ajax({
type : ‘post’,
dataType : ‘json’,
url : myAjax.ajaxurl,
context : this,
data: {
action: ‘tps_get_space_info_block_ajax’, spaceID:spaceID
},
success: function(response) {
console.log(response);
var wWidth = $(window).width();
var dWidth = wWidth * 0.8; //this will make the dialog 80% of the window
tps_show_modal(‘Space Info’, response, false, ‘OK’, dWidth);
}
});

e.preventDefault();
});

Here’s my php function it calls:

add_action(‘wp_ajax_tps_get_space_info_block_ajax’, ‘tps_get_space_info_block_ajax’);
add_action(‘wp_ajax_nopriv_tps_get_space_info_block_ajax’, ‘tps_get_space_info_block_ajax’);
function tps_get_space_info_block_ajax() {
set_query_var(‘spaceID’, $_REQUEST[‘spaceID’]);
ob_start();
include(‘../space-info-pane.php’);
$result = ob_get_clean();
$result = json_encode($result);
echo $result;
die();
}

Read more here:: Include PHP file via AJAX call

Leave a Reply

Your email address will not be published. Required fields are marked *