Skip Navigation

[Resolved] Only load a view when triggered by an acccordion button or other button

This support ticket is created 4 years, 8 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

This topic contains 17 replies, has 2 voices.

Last updated by Beda 4 years, 8 months ago.

Assisted by: Beda.

Author
Posts
#1522361

I have a project overview page with many views on it for:
- project client & agencY
- project versions
- project timing
- project crewlsit
Etc

In order to make the page load fast I would like to only load a view when the user clicks on a bootstrap collapse or accordion item or similar.

So when the user visits the page he sees an overview of titles and when he clicks on one of the titles the requested view expands and loads without leaving the main page.

This would allow the user to stay on the same page and browse the various views conveniently without having to leave the page or load all the views at once in the beginning when the page loads.

Here‘s my work in progress example page with all thr views loading on page start:
hidden link

How can I achieve that the views on this page load only when requested by the user through a click or bootstrap trigger?

Thx a lot for your help!
Tobi

#1522451

What you can do, is take the View and load it on button click (or any event) with an AJAX event, but that is custom code that we cannot support here as such.

Basically, you would output the View in a PHP function using the API here https://toolset.com/documentation/programmer-reference/views-api/
Then you'd call that PHP Function's results in a JS onclick() event, for example.
This is a good start:
https://stackoverflow.com/questions/19323010/execute-php-function-with-onclick

You would call the View's result in your PHP, and then call that function with the AJAX proposed.

If you require more help for such custom code, I suggest contacting a Consultant from https://toolset.com/contractors/

#1522493

Thx a lot Beda for the swift reply and for the helping links.

Before I go further down that road:
- do you think that is valid and smart way of doing things or would you rather set the system up in a different way?

Thx a lot for specifying
Tobi

#1522509

It's not what the developers had in mind when they created Views.
If you use advanced code to call a view it is a valid question to ask "why not create the query itself right with custom code too".

Views was created for easy query building and display, but not to populate other code or variables.

So, I'd say, if possible to not do it.

But I used similar approaches in past for similar reasons and it works because all that can fail in such code is the AJAX we write for this, when creating such custom code, views itself will just deliver its results as it would on a page.

But it is definitely worth to think about the setup if maybe even the data loaded could be shaved, so to alleviate the load time a bit.
This also depends on your SEO needs, after all.
If you need that content indexed you need to load it before - Google doesn't really consider JS loaded or altered content as "important".

#1522547

Hey Beda, wow, thank you I greatly appreciate this kind of insight. Since I am not a coder, it is often hard to decide what the right way to go is. So this sort of answer helps me a lot.

I am building an internal website for our company with lots of lists and views for our employees and freelancers to find information quickly. From contact info to project info etc. So there are specifically no SEO needs. It's all behind login and passwords.

It is important though that the pages and informations load quickly. Even if 20-30 people access the same page at the same time.

And since I am not proficient in coding everything and very happy for the toolset functionalities, I guess it sounds like this is the right way to go for me, correct?

Any other suggestions to keep the load speeds of my website up is also greatly appreciated.

Thx Beda, looking forward to your thoughts and tipps.
Tobi

#1523407

Hey Beda, so thanks to your tipps I am one step further 🙂

I have managed to create an AJAX button and call a php script on click and the php echoes an output correctly on my 'project' cpt singe page:
hidden link
(got to where it says: 'A demo of database table with PHP')

<?php echo '<p>Hello Tobi Test</p>';
?>

But as soon as I add the following code to render a view, the whole php script does not show up anymore. And the view does not show up either. Somehow the render_view code does not seem to work in my php file and breaks the call?

<?php echo '<p>Hello Tobi before Test</p>';
echo render_view( array( 'name' => 'projects-test-view-view' ) );
?>

(the test view shows up correctly on the project page when called normally from the page)

How do I have to implement the render_view code in the php file so it works correctly? Thx for your help!
Tobi

#1526485

Please create a simple PHP function in your functions.php of the theme, for example, in that function return a string, and then use that method to test in your custom code.

If that works then a View should too, but I suspect you call this somehow too early or so, is the view not ready (plugins not loaded, or similar)

#1526799

Hey Beda. Thx for your reply. I already did exactly that (see above). The test script works perfectly fine. When I exchange the ‚echo‘ test line with the above ‚render_view‘ line nothing happens. Looking forward to your thoughts.
Thx
T

#1526829

No, that is not the exact same
You call a native PHP function echo directly in the file.
Please register a function, somewhere else, like the render_view is as well.

Then, call that function in your custom code which you then call with the js.
I recall back when I did this, I added my code to a Page Template and called that page template conditionally
So the View is ready, as its inside a template, of a theme.

I cannot access hidden link to see what this suggests, but anyway, this is a highly customized code, in all cases.
We can be of limited assistance here only, this is why I first want to ensure that you can actually use 3rd party Functions in your custom code, by registering a test function.

#1528561

Hey Beda, sorry for my ignorance, this is all new to me and thank you for continuing to guiding me in the right directon, because, thx to your tipps I am proud to day :

I got the basics to work 🙂

The html, javascript and php work together now and my javascript button triggers the php function and loads the view with the following code in php:
echo render_view( array( 'name' => 'projects-sujet-list-view' ) );

But the view has no context so it ouputs all entries of the view, instead of only the ones that are relevant to the current context.

How can I give the context in the php code or via a content template, so the toolset view only outputs the currently relevant entries?

Thx a lot, almost there 🙂

#1530195

I need to dig into this myself because honestly, it is not how or what Toolset is made for / should be used for, and there are not many cases when I need to help on such scenarios

I'll have to set up quickly some view and a tab system to test what I created back then (I do not have the reference anymore, unfortunately).

Generally, JS needing PHP is only possible with the AJAX request and of course you need to pass all that what is usually available in PHP to the AJAX request so PHP can feed on it and return you some data.

It may take a while to come up with a working solution, as currently, we have a higher amount of tickets than usual, where users are stuck due to bugs or breaking sites.
I will asap come back here and have some input, but it might take until coming Tuesday.

#1534629

Thx Beda, for you continuous support and understanding. I greatly appreciate your help - and even if not many people might use this - I hope it will be also beneficial for others. I think it could be actually a quite nice way of keeping loading times of a page fast and at the same time provide direct access many lists and information on an overview page. - Also, I have troubles understanding what the purpose of the render_view function could be, if you cannot use a filter on it? But that is probably due to my amateur coding status 🙂 - Anyway, I am really looking forward to hearing from you again. This would really help me build our project tool. Thanks again! Tobias

#1538619

OK so, I cannot officially suggest or support using Views in an AJAXifieid call as we very well offer a PHP API but not a JS API.
See also https://toolset.com/forums/topic/loading-views-with-ajax/ in regard.
There are also interesting solutions at https://toolset.com/forums/topic/ajax-load-view/

In some minimal steps, you'd:

1. create a JS file (lets say in your Child Theme) where you add something like this:

Query(document).on('click', '.some-element', function(e){ //trigger element

    jQuery.ajax({
        method: 'post',
        url: object_name.ajaxurl,
        data: {
            action: 'my_custom_php_function',
        }
    }).done(function(msg) {
        // Do something when done
    });

    e.preventDefault();
});

2. Enqueue and localize the script with something like this:

wp_enqueue_script('string-handle', get_template_directory_uri() . '/string-handle.js', array('jquery'), '', true);

wp_localize_script('string-handle', 'object_name', array('ajaxurl' => admin_url('admin-ajax.php')));

3. Create a Function that does the PHP magic, let's say

function my_custom_php_function(){
	$out = do_shortcode('[wpv-post-title item="1"]');
	echo $out;
}

4. Add that function to your localized script with something like

add_action('wp_ajax_my_custom_php_function', 'my_custom_php_function');//note that here the hook is wp_ajax_, and my_custom_php_function is the name of your function, so you must change that.

5. Add an HTML element with class some-element to your site and click on it, this will show in the requests that you fired an AJAX request to function my_custom_php_function which then returns post title of item 1.

Now, this requires a post object to be passed no matter what, so if you have a view that somehow relies on the current displaying post, then you'd need to pass that either to the ShortCode, or when using the function to render View results, as the arguments.

How you find the corresponding "context" to pass, generally a post ID to relate to, probably, depends on where and how this is used.
I think in your case it could be asking for displaying related posts to the currently shown page, and hence you could try get_queried_object or get_queried_object_id of WordPress:
https://developer.wordpress.org/reference/functions/get_queried_object_id/

This can help to provide the current posts or pages context, from which you can extract the data needed to pass to the view.

Other than that I could actually not imagine any need of context, as the view will otherwise follow its internal settings.

Does this help to proceed?

#1543173

Hey Beda, thank you so much for the detailed reply, I think we almost got it now. I've managed to make the button with the AJAX request and calling the php function which returns the correct view.

You can try it here:

1. hidden link
(scroll down and click on the red 'Show Version List Test' button)

2. you will see that the list loads on the page with:

this content template:
hidden link

and this JS:
hidden link

and this PHP:
hidden link

BUT: it loads ALL posts and not just the ones related to the current page.

Just below the list you see the correct loaded list under the title:
'Versions - Hierarchical View'
Here I've used the normal way of showing a view and it shows up correctly, only the related posts show.

The only thing I am struggling with is your last step 5. You are correct, I think the render_view needs to know the context (the current ID of the page it is on) to only show the related posts and not all posts. Right now, it is incorrectly showing all posts. How can I get the current ID and pass it to the render_view?

Thanks a lot!
Tobias

#1545527

As mentioned, you need to pass the settings, like so:

$out = do_shortcode('[wpv-post-title item="1"]');

Or,

//Example 1 
$args = array(
    'title' => 'My View name',
    'myattribute' => 'myvalue'
);
echo render_view( $args );

Here "myattribute" is a ShortCode attribute set in a View Query, and "myvalue" the value passed to it.
So you can select posts related to the one set in the ShortCode attribute, and pass that in your PHP.