Using the Primefaces ajax feature to pass a parameter to JavaScript for callback execution

Struggling with sending a Primefaces bean property to JavaScript directly in order to open a new page and write the content of the bean property into it.

The version of Primefaces being used is 4.0.

A command button that is being utilized looks like this:

<p:commandButton id="buttonId" update="buttonId, otherComponentId"
    value="press me" process="@this" actionListener="#{homeController.myMethod}"
    oncomplete="handleComplete(xhr, status, args)">
 </p:commandButton>

In the handleComplete javascript function, 'args' is undefined while 'xhr' and 'status' are not. The definition of the javascript function is as follows:

function handleComplete(xhr, status, args){
    var w = window.open();
    w.document.open();
    alert(xhr.responseText.substring(100));
    alert(status);
    alert(args);
    var d = '<head></head><body>'+ args.firstParam +'<body>';
    w.document.write(d);
    w.document.close();
}

The first alert displays the page correctly, the second one results in a parse error, showing: Uncaught TypeError: Cannot read property 'firstParam' of undefined

The intention is to pass a string like this through 'args':

public String MyMethod() {
    RequestContext context = RequestContext.getCurrentInstance();  
    context.addCallbackParam("firstParam", "my string");
      return "";
}

and be able to access it in JavaScript using args.firstParam.

The method gets called (confirmed with working printscreens).

This approach needs to be tried instead of setting the text into a

<h:outputText id="myText" escape="false" rendered="true"
            value="#{homeController.property}" />

and then extracting the innerHTML of this element since what is obtained with innerHTML might not match the string variable in the bean. This method does work but not entirely as desired. Curious about why the args object is undefined or any other way to manage the bean property from JavaScript effectively. Thank you.

Answer №1

Ensure that the first step is confirming whether your method is being invoked. Introduce some logging or debug statements in your method to verify its invocation.

If not, consider including the process attribute in the button element and setting it to @this.

If at this point your method is being called, then there may be a validation issue on your page.

I recommend invoking my methods in actionListener rather than in action, and remember to include parentheses at the end. Learn more about the differences between action and actionListener

Try the code snippet below:

<p:commandButton id="buttonId"
 value="press me"  actionListener="#{homeController.myMethod()}"
 process="@this"
 oncomplete="handleComplete(xhr, status, args)">
</p:commandButton>

Regarding the error message "firstParam" is undefined instead of "args" is undefined, validate that the value of firstParam is not null.

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

Issue: NG0204: Unable to find solutions for all parameters in NzModalRef: (?, ?, ?)

I'm currently working on an Angular project utilizing the NZ-Zorro library, and I'm encountering difficulty understanding which parameters are causing issues with NzModalRef when attempting to run the test code coverage. The error message display ...

Switch the contenteditable HTML attribute in a dynamically generated table using PHP

Despite finding numerous articles and solutions, my code still refuses to work. What could I be overlooking? Below is a snippet of the code where the crucial part is marked at the comment '! HERE') <!-- Table with grades --> <table clas ...

Is there a way to prevent my timer from resetting whenever I refresh the page?

Hey everyone, I'm new to coding and I could really use some help here. I have this code for a timer but I'm struggling to make it work properly even after refreshing the page. My goal is to keep the timer running smoothly, but I'm not sure w ...

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

experiencing an excessive amount of re-renders after transferring data to a distinct component

At the moment, I have implemented this logic to display data based on the results of a graphql query, and it is working well: const contacts = () => { const { loading, error, data } = useUsersQuery({ variables: { where: { id: 1 }, ...

A technique for making the placeholder flash when an input textfield loses focus

I am trying to implement a blinking effect on the placeholder text when the input field loses focus. Here is the HTML code I have written: <input type="text" id="keyfob" class="customform col-sm-12 text-red" data-required='true' placeholder= ...

What steps can be taken to resolve the delay in transition when clicking on "read less

I implemented a transition effect for the Read More and Read Less buttons, however, there seems to be a delay on the transition when clicking on the Read Less button. This delay was not intentionally set by me. How can I resolve this issue and also apply a ...

What is the best way to utilize the outcome of the initial API request when making a second API call in AngularJS

Looking to utilize the response of a first API call in a second API call. The situation is such that I need to fetch data from the first API and use it in the second API call. I believe a synchronous API call would be necessary. While attempting to imple ...

Local storage has the limitation of being able to store only a single object at a time, rather

This code is designed to store product details in a local storage variable whenever a user visits a product page, with the intention of remembering the last visited products. However, the variable currently only retains one product at a time instead of add ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

Using Javascript to manipulate the Window object in Visual Studio Code

Currently delving into the world of Javascript and experimenting with a code snippet from a recommended book. The book mentions that the window object should be visible in a browser environment. Despite having Node.js set up, I encountered an issue when ex ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Instructions for concealing a parent div and substituting it with a different div upon the user's click on a button nested within the parent div

I am working on a component that consists of two buttons. The goal is to hide the entire component when one of the buttons is clicked and replace it with another component. Although I have successfully hidden the clicked button, I am struggling to hide th ...

Obtaining environment variables from the host and accessing them in a react .env file

For my ReactJs application, which incorporates multiple profiles, I am in the process of setting it up to run across a development environment, QA environment, and production environment. To achieve this, I am looking to establish some environment variabl ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

Combining an if-statement with an HTML button within a single function in JavaScript

I'm currently developing an HTML table that includes fields that must be filled, but I want to allow one of the fields to be optional. The structure of my code is as follows: name.html ... <table> <tr> <td>Number 1:</td& ...

Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help. I recently started delving into TypeScript due to my work with Angul ...