Unable to invoke backing bean method using JavaScript

I have been able to successfully write JavaScript code in a bean method during application start.

However, I am facing an issue where the JavaScript function calls the bean method and returns values when the application is initially started. When I click on the button, it does not call the bean method again. It seems to only call the bean method during application startup. Here is my button:

<p:commandLink oncomplete="myRemote();" title="my button"
               />

This is my JavaScript function:

 function myRemote() {
 ${myBackingBean.actionMyValues()}
 }

Below is my Bean class:

@Controller
@Scope("view")
public class MyBackingBean implements Serializable {

public String actionMyValues() {

    String js="";
    /*getting some values from database and adding it to javascript variables.*/
    js += "alert('alert')";//
    return js;
}
}

Answer №1

To invoke JavaScript from your managed bean, you can utilize the

org.primefaces.context.RequestContext
class:

String js="";
/*retrieve data from database and assign it to JavaScript variables.*/
js += "alert('alert')";
RequestContext.getCurrentInstance().execute("js");

UPDATE

Another option, as mentioned in the comments, is using a p:remoteCommand (https://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml)

The remote command serves as a replacement for your custom JS function:

<p:commandButton value="My button" type="button" onclick="myRemote()" id="btnRemote" />  

<p:remoteCommand name="myRemote" actionListener="#{myBackingBean.actionMyValues()}"/>   

If you still need to trigger JavaScript from your bean, you will still require the use of the RequestContext.

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

What are the methods used in TypeScript to implement features that are not available in JavaScript, despite TypeScript ultimately being compiled to JavaScript?

After transitioning from JavaScript to TypeScript, I discovered that TypeScript offers many features not found in JS, such as types. However, TypeScript is ultimately compiled down to JavaScript. How is it possible for a language like TypeScript to achie ...

Unable to retrieve props from server-side page to client-side component in a Next.js application router

Currently, I am utilizing app router alongside Next.js version 13.5. Within my /dashboard page (which is a server component), there is an ApiKeyOptions client component embedded. However, when attempting to pass props from the dashboard page to the ApiKeyO ...

Press the button to eliminate

Is there a way for users to add tags by typing text and then clicking on an add button? Once the tag is added, it appears with a delete button, allowing users to manage their list of tags. The JavaScript code below enables users to add tags successfully, ...

Reset the change function after the click function has been executed

I am currently using the change event handler for my input elements and then prompting users with questions. All of my code resides within a click function. I would like to allow users to answer the questions again, without retaining their previous data. S ...

Input text fields are restricted to only accept numerical values

I recently tried out the Jquery Numeric plugin, but unfortunately I discovered that it does not work on FireFox 3.6 on OSX as it does not allow pasting. Therefore, I am in search of a different Jquery plugin or Javascript snippet that specifically allows ...

The JSSOR Slider encounters issues when trying to display dynamic content

I've created a basic HTM page and I'm attempting to incorporate the JSSOR Slider. Unfortunately, it doesn't seem to be functioning properly. Despite checking the console for errors, nothing seems to be out of place. When clicking on the arro ...

You have attempted to make an invalid hook call in the react chat app. Hooks can only be called within the body of a function component

Encountering problems like manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. **Important Error Message/User Notification:** react-dom.development.js:20085 The above error occurred in the <WithStyles(ForwardRef(AppBar))> component: Arrange ...

The visual representation is not being generated (three.js)

I recently designed a basic scene in three.js, however I am facing an issue where it does not seem to work with the canvas renderer, even though it should work correctly. Here is the code: http://jsfiddle.net/PRkcJ/ The scene only functions properly when ...

Encountering issues when trying to execute the debugger on Eclipse

I attempted to utilize the debugger for Java SE in Eclipse (Luna), but encountered issues as breakpoints failed to toggle. When I tried running the debugger on a class named 'Execute', this is the result: The Issue https://i.sstatic.net/k1CDW.j ...

When using Node.js with Nginx, requests are timing out at the Nginx level before the processing is completed in Node.js

I have a setup where I use Nginx and Node.js servers. The process involves uploading a file from a browser to Nginx, which then forwards it to Node.js for processing. However, I've encountered an issue when dealing with large files - the upload crashe ...

JSF not triggering Ajax event

I'm facing an issue where the Ajax event is not firing to call the actionListener or update the second select menu. Can anyone help me with what might be causing this problem? <p:selectOneMenu value="#{player}" converter="playerCon ...

Filter out elements with identical dates from a JSONArray

One of the tasks I have is to sort a JSONArray that contains JSONObject data. The structure of the JSON looks like this: [ { "id": 582, "isTransaction": false, "toDate": "2015-08-26 16:12:00.0", "fromDate": "2015-08-24 15:11:00.0", " ...

The promise was formed in a handler and left unfulfilled in Bluebird

Initially, I understand the need to return promises in order to prevent the warning. I have attempted returning null as suggested in the documentation here. Take a look at this code snippet which is used within Mongoose's pre-save hook, though the war ...

Understanding Callback Functions in Google Maps API: How Asynchronous Calls can Impact JavaScript

Seeking to enhance some code, I'm exploring the utilization of Google Maps for longitude and latitude calculations. Initially encountering an issue with the asynchronous nature of Google maps data retrieval, a kind individual proposed a solution. Desp ...

Should I insert the override generated code where the cursor is currently placed?

As a dedicated user of eclipse mars, I must say it never fails to deliver. However, one small annoyance is the placement of the generated code when using the "Override/Implements methods..." feature. It always ends up at the bottom of the java source file ...

Navigating up and down effortlessly using bootstrap

My webpage has a collapsible form located near the bottom, but when it's opened users must scroll down to see all of it. Is there a way to automatically scroll down when it's opened and then scroll back up when closed? Take a look at my code: & ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Stopping data-ajax attributes from running

Here is a link I have along with its corresponding fiddle: <a class="update noClick" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#vote11" href="/Tutors/RateNegative/11" onclick="return window.confirm('Are you sure?');">qwer ...

Implementing a django like feature using ajax requests

I am currently working on a template where I have a link for my article: <div id="voteUp"> <h4><a href="{% url "vote_up" article.id %}">Like {{article.up_vote}}</a></h4> </div> My goal is to increase the vote count for ...

JavaScript: Utilizing numbers to extend a sequence

My code is saved in a Google Sheets document and here is how it looks: ss = SpreadsheetApp.getActiveSpreadsheet(); function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = [ {name: "10 Rows", functionName: "TenRows"}, ...