Using get_template_part with Ajax
-
So I have read some pretty good blog posts and forum responses to help me along the way with this and it is just about finished. Since this is the first time I have worked with ajax and am not proficient in javascript, I am having trouble with some of the concepts and applying them correctly.
The goal in a nutshell: I would like to load a php file which executes shortcodes via an ajax request that executes when a user clicks on a button with the id #all-options. I am using ‘include’ instead of ‘get_template_part’ because my template file needs access to variables on the main page, but the solution should be the same for either method.
As far as I know, I am implementing ajax correctly via my functions. Here is the relevant code:
Enqueueing the ajax script
function phantom_scripts() { global $child_dir; /* Ajax Requests */ wp_enqueue_script( 'ajax-stuff', $child_dir . '/js/ajax.js', array( 'jquery' ), true ); } add_action( 'wp_enqueue_scripts', 'phantom_scripts' );
Ajax Handler
function portfolio_ajax() { include( 'templates/home-portfolio-layout.php' ); die(); } add_action('wp_ajax_nopriv_portfolio_ajax', 'portfolio_ajax'); add_action('wp_ajax_portfolio_ajax', 'portfolio_ajax'); wp_localize_script( 'ajax-stuff', 'ajaxStuff', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Now here is the actual ajax.js which is throwing me off. I’m not sure how to simply load the template file into the DOM, so I included an alert to show me whether or not it was retrieving the php template:
(function ($) { $(function () { $('#all-options').click(function() { var data = { 'action' : 'portfolio_ajax' }; $.post(ajaxurl, data, function(response) { alert('Here it is:' + response); }); }); }); }(jQuery));
So when I click on #all-options, I see an alert which prints the template file as a string. I am happy because this means that the ajax is working, but I’m confused because I don’t know how to execute the php on its own and display the results in the DOM. How do I simply execute the action and display the data?
- The topic ‘Using get_template_part with Ajax’ is closed to new replies.