How can I return a view from an ajax call

Hey there!

I have a simple view (“resources/views/partials/post-preview.blade.php”) containing markup for my posts.

When displaying the page initially everything is working fine: in my page I just loop the list of posts (returned by the controller) and include the post-preview to display all of them individually. However once the page is loaded and I submit ajax queries to my custom WordPress hook (wp_ajax_load_posts) I don’t know how to access the “post-preview” view to return formatted HTML.

I couldn’t find much documentation on how to approach AJAX stuff with Sage 9 so a little help would be greatly appreciated. Thanks!

1 Like

This is not a direct answer to your question and there might be better solutions to this, but I’ve solved something similar with Ajax Load More. The plugin allows the use of PHP templates to format the output of any posts loaded with ajax, so I took what was equivalent to your post-preview.blade.php and used PHP in that file instead of laravel blade. Then I imported the blade file as a template into the plugin and it worked.

If you’re just looking for loading more posts through ajax, I can recommend this option. It basically took 5 minutes, worked right out of the box and saved a ton of programming time.

Thanks a lot for the answer but I’m trying to avoid depending on plugins for something like this, especially since most of the code is already done. I guess I’ll keep it in mind as plan B in case!

In older versions of Sage/Root I used to simply get the template using get_template_part() but I’m still adjusting to the new structure and would love an elegant way.

Hey @frkparent - I think what you will need to do is render the Blade template using PHP in your AJAX hook, and then return the result.

You can render a Blade template in PHP using App\template(). Something like this:

add_filter('wp_ajax_load_posts', function () {
    echo App\template('');

If you need to pass data from the controller to the partial, take a look at @MWDelaney’s post here: Shortcodes that use Blade templates and get Controller data.


That was it! So simple, thanks a lot for your help!!

1 Like

Hey, just a followup: using App\template is not working on a new Sage version (Controller was updated to 2.1.0).
For custom functions I have to use Controllers\App::myFunction() to make it work if used inside setup.php for example.

Still don’t know how to make it work in custom controllers though. echo Template() functions are not working, since namespaces are different now, namespace App\Controllers;instead of just namespace App;.

Any tips for the new Sage version? Thanks!

Edit: made it work using echo \App\Template() (gotta switch to a different namespace, since the file I’m in uses namespace App\Controllers;. And you do that using prepended slash.

1 Like