In a plugin file, which acts a page template, I am including a php file that generates some content on the page.
A simplified example:
<div id="content">
<?php include('path-to-file.php'); ?>
</div>
I want this div to "refresh" when a certain element on the page is clicked. In a non-wordpress environment, I could just use .load() to grab the .php file from the server and put it into the div, like so:
$('#content').load('path-to-file.php');
But in Wordpress, you can't access files directly like this, it throws a 404 error.
The official method of grabbing stuff from the server via ajax is to go through Wordpress's admin-ajax.php with an action set, like so:
PHP:
add_action('wp_ajax_tps_refresh_cart_display', 'tps_refresh_cart_display');
add_action('wp_ajax_nopriv_tps_refresh_cart_display', 'tps_refresh_cart_display');
function tps_refresh_cart_display() {
// Grab php file from server
$result['phpfile'] = 'path-to-file.php';
$result = json_encode($result);
echo $result;
die();
}
JS:
$.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl, //we can use this value because in our php file we used wp_localize_script
context:this,
data : {action: 'tps_refresh_cart_display', },
success: function(response) {
//load the fetched php file into the div
$('#content').load(response.phpfile);
}
});
But I'm struggling to figure out how to grab the php file and actually get Wordpress to let me load it into the div. Fetching the file this way and using .load() after the ajax call returns it still throws a 404. Is there some way I'm supposed to localize a php file, like wp_localize_script does for js scripts?
Am I still going about this wrong? Any help appreciated.