JavaScript code failed to run

I am currently attempting to invoke a JavaScript script to export a chart from the PrimeFaces chart component. The issue I am facing is that the base64str variable appears to be null, and the script responsible for populating this value is not being called for some unknown reason:

XHTML code :

<p:chart id="chart" type="line"  widgetVar="chart" model="#{cont.lineModel}"  style="height:550px;width:1800px">
           <p:ajax event="itemSelect" listener="#{cont.itemSelect}" update="growl" />                             
    </p:chart>
    <p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
            onclick="exportChart();" actionListener="#{cont.submittedBase64Str}" 
           />
        <h:inputHidden id="b64" value="#{cont.base64Str}" />                     


<script type="text/javascript">
        function exportChart() {
        img = chart.exportAsImage();
        document.getElementById('hform:b64').value = img.src;

        }
    </script>

Controller :

public void submittedBase64Str(ActionEvent event){
// You probably want to have a more comprehensive check here. 
// In this example I only use a simple check
if(base64Str.split(",").length > 1){
    String encoded = base64Str.split(",")[1];
    byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
    // Write to a .png file
    try {
        RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
        ImageIO.write(renderedImage, "png", new File("D:\\out.png")); 
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Thank you

Answer №1

Update the onclick attribute to say onstart.

    <p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
  onstart="exportChart();" actionListener="#{cont.submittedBase64Str}" />

This modification should trigger the JavaScript function.

MODIFICATION

You also have to ensure that img and chart are defined in your function.

Answer №2

chart object is essentially the PrimeFaces JS widget. When setting it up, you would define the variable widgetVar:

<p:chart ... widgetVar="chart"

Subsequently, accessing the chart object in your JS code can be done as follows:

PF('chart')

It's crucial to utilize the PF function for retrieving widgets starting from PrimeFaces 4.0.

As a helpful tip, consider keeping your img variable local rather than global:

var img = chart.exportAsImage();

By doing this, img will only be defined within the confines of the function.

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

Values returned by XmlHttpRequest

When it comes to returning data from an XmlHttpRequest, there are several options to consider. Here's a breakdown: Plain HTML: The request can format the data and return it in a user-friendly way. Advantage: Easy for the calling page to consume ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this: <p class="level_1">List item 1</p> <p class="level_2">List item 2</p> <p class="level_3">List item 3</p> <p class="level_1">List item 1</p& ...

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

``The importance of properly formatting a text string before encoding it into

Currently in the process of converting an XML document to JSON via a PHP backend and then sending it back to the frontend using AJAX. This is achieved through the following code snippet: print_r(json_encode($result_xml)); If you want to view the response ...

Utilizing the same WebDriverJS instance repeatedly

As a beginner in Selenium, I successfully launched a website using the following Node.js code snippet: var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder() .forBrowser('chrome') .build(); console ...

Handling multiple render calls and rerenders in React function components with setTimeout (best practice for firing multiple times)

Is there a way to optimize the Notification component in my App, so that the setTimeout function is only initialized once even if multiple notifications are pushed into the state? function Notification(props) { console.log("Notification function compone ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

Mandating the inclusion of a directives controller in conjunction with other necessary controllers

Two directives are nested within each other, with one requiring the other using require: '^parentTag' . Both directives have their own controllers. In the parent directive, I can access its controller as the fourth argument in link: function(scop ...

Is there a way to add another item to a repeated DOM element without having to modify the ng-repeat scope?

I am working with a list of items using ng-repeat <div layout="column" class="md-whiteframe-1dp" ng-repeat="item in child.items track by item._id" id={{item._id}}child> </div> I am looking to add an additional DOM ele ...

Massive Memory Drain Due to XMLHttp POST Request

Is there a way to prevent XHR POST Memory leak in my web app? I have searched extensively for solutions but have not found any satisfactory answers. My issue is similar to the one described in this blog post that outlines the problem without offering any f ...

Accessing stored web pages / Browser as an interactive interface

I have a couple of questions I need help with. The first one is about how to open a saved HTML file in a browser without an internet connection. Next, I'm looking for advice on using the browser as a user interface for a desktop image viewing program ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Is JavaScript Promise Chaining Allowed?

I have a question regarding my code, despite it currently functioning correctly. Specifically, I'm wondering if the sequence of promises in my database is valid. Promise 1 must be fulfilled before moving on to Promise 2 because I rely on the data and ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

Issue encountered when attempting to execute a JavaScript AppleScript from another JavaScript AppleScript due to permissions error

I am in the process of organizing my .applescript files by separating them into different ones for better organization. Within my JS AppleScript file named Test.applescript, I am attempting to execute another JS AppleScript file called Group Tracks Depend ...

Anticipate that the typescript tsc will generate an error, yet no error was encountered

While working in the IDE to edit the TypeScript code, an issue was noticed in checkApp.ts with the following warning: Argument type { someWrongParams: any } is not assignable to parameter type AddAppToListParams. Surprisingly, when running tsc, no error ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

Tips for inserting a blank space into a text box

It feels like such a simple issue, but my function is incorrectly returning "1" instead of just an empty space "" in my textbox. <td><input type="button" value="Space" name="Space" onClick='document.firstChild.search.value = document.firstCh ...