Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly.

Within the DirectoryViewer, the MediaViewer is displayed using a zone:

<t:zone t:id="MediaViewZone" id="MediaViewZone">
    <t:MediaViewer fileToShow="fileToShow"/>
</t:zone>

When a user clicks on a filename link, the fileToShow property is updated and the zone is refreshed accordingly:

Object onActionFromFileSelection(File file) {
    this.fileToShow = file;
    return MediaViewZone.getBody(); // AJAX request, returning zone's body
}

This setup prevents the whole page from refreshing when switching between files, providing a better user experience.

The MediaViewer has three blocks for displaying different types of media. Currently, it supports text, pdf, or image files. For images specifically, I want to incorporate zoom functionality using a JavaScript library.

Up until this point, everything is working as expected.

However, when an image file is selected, the corresponding block should display like this:

<t:block id="image">
 <section id="focal">
     <h1>Use the mousewheel to zoom on a focal point</h1>
     <div class="parent">
         <div class="panzoom">
             <image src="${FileLink}"/>
         </div>
     </div>

     <div class="buttons">
         <button class="zoom-in">Zoom In</button>
         <button class="zoom-out">Zoom Out</button>
         <input type="range" class="zoom-range"></input>
         <button class="reset">Reset</button>
     </div>
     <script src="${context:layout/js/jquery.mousewheel.run.js}"></script>
 </section>
</t:block>

The issue arises when the script inside the block does not get executed initially. Upon inspecting the source code, the script is missing. However, if I perform a hard refresh (CTRL + F5), the script appears and runs successfully. It seems that the script is not executing when returned within the AJAX zone. The reason behind this behavior could be related to how the onActionFromFileSelection method functions or if there is a need to use eval() to trigger the browser to process the script. This problem has me puzzled.

I've spent a considerable amount of time trying to resolve these issues but haven't found a definite solution yet. 1) Why does the script disappear from view source after loading the zone by clicking a file? 2) How can I ensure that the JavaScript loads when showing the image block?

Your assistance in resolving this matter would be greatly appreciated.

Answer №1

Here is a solution to consider:

@Inject
private AjaxResponseRenderer ajaxResponseRenderer;

@Inject
@Path("context:layout/js/jquery.mousewheel.run.js")
private Asset runLib;

Object onActionFromFileSelection(File selectedFile) {

    this.fileToShow = selectedFile;

    ajaxResponseRenderer.addRender(MediaViewZone);
    ajaxResponseRenderer.addCallback(new JavaScriptCallback() {

        @Override
        public void execute(JavaScriptSupport jsSupport) {

            jsSupport.loadJavascriptLibrary(runLib);
        }
    });
}

Answer №2

I made a workaround to solve this issue, although it's not the most elegant solution. I am sure there is a more efficient way to handle it.

What I did was modify my context:layout/js/jquery.mousewheel.run.js file into a function called "addImageScript" that only runs when called. Then, I imported the script in the head section to ensure it is always available using the following code:

@Import(library={
        "context:layout/js/jquery.min.js",
        "context:layout/js/jquery.panzoom.js",
        "context:layout/js/jquery.mousewheel.js",
        "context:layout/js/jquery.mousewheel.run.js",
})

Now, I just have to remember to call that script when the block containing the image should be displayed. To achieve this, instead of including the script in the AJAX response like before:

<script> addImageScript() </script>

I realized that approach wouldn't work as intended since the call never executes. So, I added the following to my delegate method:

javaScriptSupport.addScript("addImageScript()");

While this solution works, it's not ideal because it means the extra js file is loaded every time the page loads. If anyone has a more optimal solution, I'm open to suggestions and will appreciate any better answers with an upvote.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Serving Files in Express JS: the benefits of serving files directly from memory compared to serving static

Should I keep images and other assets in memory or serve them from static assets? Will often-requested static assets be stored in memory? Does anyone have insight into the performance implications of this decision? ...

Unable to retrieve information from a child component in React

So, this component acts as the main container class TaskList extends React.Component { state = { task: '', } handleTaskClick = () => { taskArray.push({id: idCount, text: this.state.task, completed: false}) idCount++ this. ...

Load texture programmatically instead of using MTL files

I've successfully loaded an OBJ file and linked it with an MTL to provide a texture. However, I'm struggling to specify which texture should be associated with the model directly in the code; it seems that the texture only appears on the model if ...

Guide on creating a live connection between a slider and a canvas

Currently, I am working on implementing a slider that can dynamically adjust a specific value in the canvas, such as the radius of a circle. Although my code works as intended, I would like the canvas to update in real-time as I move the slider instead of ...

Differences between XMLHttpRequest and HttpRequestThere are several distinctions

Can somebody tell me the unique benefits of using an XMLHttpRequest in a web page that cannot be accomplished with a standard HttpRequest? ...

While attempting an AJAX request with jQuery, I encountered the following error message: "Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN"

I encountered an issue that says: ` throw err; // Rethrow non-MySQL errors ^ Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN ` while attempting a jQuery AJAX get request, and I'm unsure of the cause. My backend is built using node.js a ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

I am seeking a solution to this error that occurs whenever I attempt to call a function using a button

Issue " _ctx.hello is not a function TypeError: _ctx.hello is not a function at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/di ...

You can use AJAX, JQuery, or JavaScript in PHP to upload a total of 7 files by utilizing 7 individual file input

My client has a unique request - they want to be able to upload a file in PHP without using the traditional <form> tag or a submit button. While I am familiar with file uploads in PHP, I am unsure of how to achieve this without utilizing the <for ...

The Power of Javascript in Enhancing Lightbox Experience

I am trying to enhance an image outputted by JavaScript with Lightbox functionality. Since the image link is dynamically created, I am approaching it this way! Despite searching on Stack Overflow, I have not found a solution that fits my needs... The cur ...

"Troubleshooting: Issue with ng-click in AngularJS not triggering ng-show

I can't figure out why my ng-click isn't showing the ng-show message. I've tried searching for a solution but no luck. Here is my controller function: $scope.showLogoutMessage = function() { $scope.logoutmsg = true; }; This is my Logi ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Create a Bootstrap modal that includes a checkbox option to prevent it from appearing again in

I am attempting to display a bootstrap modal upon body load based on a value retrieved from a MySQL database. The bootstrap modal is included in the body and shown successfully depending on the database value using the following code snippet: $results ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

What is the best way to ensure my php variable is easily accessed?

Recently, I've been working on implementing a timer and came across the idea in a post on Stack Overflow. <?php if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username'])) { //secondsDif ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...

By utilizing jQuery, I am orchestrating the movement of a series of div elements within a container with the simple click of a button

A group of div elements located within a container. When the button is clicked, the train should start moving. <script> $('document').ready(function(){ $("button").click(function(){ $("#train").animate({left: "300px"}, 2000); ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

The process of incorporating a function into a website's source code using a web driver

In the source code, there is a button with an onclick event to change the paragraph content. However, the code provided does not seem to be functioning properly. ((JavascriptExecutor) this) .executeScript("function test123() { y=docume ...