Having issues with executing JavaScript returned from Java in YUI Dialog using an ajax request due to scope limitations

Currently, I'm dealing with a YUI dialog which sends a form to a Java servlet. The servlet responds with HTML and JavaScript, which I then insert into a div on the page and evaluate the enclosed JavaScript code.

However, I encounter an issue where the Firebug console displays an error message stating "YAHOO is not defined" immediately upon the servlet's response.

Although I haven't included the YUI js files in the servlet because I believed the files in the main page's head section would be sufficient. When I remove any references to YUI from the returned JavaScript, everything runs smoothly.

How can I prevent this error from occurring as soon as the servlet returns?

The content returned by my servlet looks something like this:

<div id="features">some html to display</div>
<script id="ipadJS" type='text/javascript'>
var editButton1 = new YAHOO.widget.Button('editButton1', { onclick: { fn: editButtonClick, obj: {id: '469155', name : 'name 1'}  } });
var editButton2 = new YAHOO.widget.Button('editButton2', { onclick: { fn: editButtonClick, obj: {id: '84889', name : 'name 2'}  } });
</script>

Below is the code I used to create the dialog. The handleSuccess function is used to place the servlet's response onto the page, triggering the 'YAHOO not defined' error even if the JavaScript isn't explicitly added to the page:

YAHOO.namespace("ipad");

YAHOO.util.Event.onDOMReady(function () {

    // Remove progressively enhanced content class just before creating the module
    YAHOO.util.Dom.removeClass("createNewFeature", "yui-pe-content");

    // Define various event handlers for Dialog
    var handleSubmit = function() {
        this.submit();
    };
    var handleCancel = function() {
        this.cancel();
    };
    var handleSuccess = function(o) {
        var response = o.responseText;
        var div = YAHOO.util.Dom.get('features');
        div.innerHTML = response;
    };


    var handleFailure = function(o) {
        alert("Submission failed: " + o.status);
    };

    // Instantiate the Dialog
    YAHOO.ipad.createNewFeature = new YAHOO.widget.Dialog("createNewFeature", 
                            { width : "450px",
                              fixedcenter : true,
                              visible : false, 
                              constraintoviewport : true,
                              buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
                                      { text:"Cancel", handler:handleCancel } ]
                            });

    // Validate the entries in the form to require that both first and last name are entered
    YAHOO.ipad.createNewFeature.validate = function() {
        var data = this.getData();
                return true;
    };

    YAHOO.ipad.createNewFeature.callback = { success: handleSuccess,
             failure: handleFailure,
             upload: handleSuccess };

    // Render the Dialog
    YAHOO.ipad.createNewFeature.render();

    var createNewFeatureShowButton = new YAHOO.widget.Button('createNewFeatureShow');

    YAHOO.util.Event.addListener("createNewFeatureShow", "click", YAHOO.ipad.clearFeatureValues, YAHOO.ipad.clearFeatureValues, true);

    var manager = new YAHOO.widget.OverlayManager(); 
    manager.register(YAHOO.ipad.createNewFeature);
});

Answer №1

Depending on your specific needs, one approach could be to generate buttons dynamically based on server response. This can be achieved by returning JSON or XML data containing the necessary variables, and then using that data to create the buttons. Here is a basic example:

var reply = eval('(' + o.responseText + ')');

var editButton1 = new YAHOO.widget.Button('editButton1', 
                     { onclick: { fn: editButtonClick, 
                      obj: {id: reply[id], name : reply[name]}
  } })

If you prefer to append a script node, you can try the following method:

   var response = o.responseText;

   var snode = document.createElement("script");
   snode.innerHTML = response;
   document.body.appendChild(snode);

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

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Can you identify the programming language used in this code snippet? - {"html":"<section class="page">

I've been approached to assist with a friend's company website since the original developer seems to have disappeared. Apologies if this question is too basic for this forum, and please forgive me if I am not in the right place to ask it. The m ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Three.js: transforming textures into data textures

Currently, my goal is to create a delayed webcam viewer using javascript, utilizing Three.js for its WebGL capabilities. At the moment, I am able to capture frames from the webcam and display them after a specified time interval using canvas and getImageD ...

real-time update of gauge value from soap

I am trying to update the value shown in my justgage widget with the value returned from $("#spanrWS_Measured").text(data[0]);. The current value is 123. Any assistance would be greatly appreciated. See the complete code below. <script src="scripts/r ...

Integrate the complete Mozilla pdf.js viewer into a Vue.js application using webpack through vue-cli

I am trying to integrate the full Mozilla pdf.js viewer into a Vue SPA. After reading a Stack Overflow post with an accepted solution, I still can't seem to get it to work. I keep encountering the 'Uncaught SyntaxError: Unexpected token <&apo ...

Leveraging ajax for showcasing page content in a floating div container

I am in need of creating a button on my page that, when clicked, will display a floating div above the page and load another internal page. I believe this can be achieved using Ajax, but I have no experience with it and don't know where to start. Her ...

Transfer information from python-cgi to AJAX

Currently, I am in the process of creating a UI version of the find command found in Linux. In this implementation, I receive the location and filename parameters for the find command through a CGI form that has been built using Python. When the user submi ...

Understanding the mechanisms of Promise functionality within Typescript can be challenging, particularly when encountering error messages such as "type void is not

Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any type: The issue arises with a function that returns a promise: sav ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Creating a plane in Three.js using points along different axes

My goal is to construct a plane that intersects the points (2, 3, 12) on the x, y, and z axes respectively (equivalently, the equation of the plane is 6x + 4y + z = 12). So far, I have attempted to generate a flat plane and rotate it around the three axes ...

Using the XMLHttpRequest object for AJAX file uploads that are compatible with Internet Explorer 9

Seeking help with uploading a file using ajax. The current code works on all browsers except for i.e 9 and older versions. I need to find a solution that will also work on i.e. Some suggestions have been to use an iframe, but I don't see how that res ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Modifying the autocomplete feature to showcase options in a dropdown menu

I have a form that requires country states to be displayed in a dropdown menu. Despite having autocomplete functionality, I am only able to see the response as an array in the console.log when searching for a specific state. I have tried to switch from aut ...

Tips for displaying a category name only once if it has already been rendered in a map function

My scenario involves a variety of categories in which pharmaceutical drugs are classified. Each individual drug belongs to a specific class. Currently, my code iterates through all the categories from the category array and places drugs underneath them if ...

Is it possible to search for a value within an array of objects in MongoDB, where the value may be found in any object within that array?

Here is the schema: {"_id":"_vz1jtdsip", "participants":{ "blue":["finettix"] "red":["EQm"] }, "win":"red"," __v":0} I have multiple documents l ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

A new update is available for the UpdatePanel and ModalPopup Extender

I have structured my form as follows: <asp:Panel runat="server" Id="xyz"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> 'Gridview featuring edit and delete options ...

Creating registration and login forms using an express server

Currently, I'm in the process of creating a basic website on my localhost that incorporates a signup form along with other essential HTML elements. The setup for the signup procedure went smoothly as planned. When a user completes the form and submits ...