The Dojo ready function is failing to execute upon receiving an AJAX response

There are two forms that I have defined as follows:

Home.jsp:-

 <!DOCTYPE html>
 <html>
 <head>
 <style type="text/css">
 @import "../Script/dojo-1.10/dijit/themes/claro/claro.css";
 </style>    
 <script type="text/javascript">
 dojoConfig = {
    isDebug: true,
    parseOnLoad : true
 }
 </script>
 <script type="text/javascript" lang="JavaScript" src="../Script/dojo-1.10/dojo/dojo.js"></script>
 <script type="text/javascript">
 require(["dojo/parser","dijit/form/Button",      
 "dojo/domReady!"],function(parser){
  //parser.parse();
  alert("From Require");
  });
  function getWelcomeJsp(){
  var loadResponse = dojo.byId("loadResponse");
   dojo.xhrPost({
        url:"Welcome.jsp",
        handleAs:"text",
        load:function(data){
        dojo.style(loadResponse,"display","block");
        loadResponse.innerHTML = data;
        return data;
    },
    error:function(err){
        alert("error"+err);
    }
    });
    }
    </script>
    </head>
    <body class="claro">
   <table>
   <tr><td valign="bottom">
   <a href="Welcome.jsp">This Is Hyperlink</a>
   </td></tr>
   <tr>
   <td>
   <label for="empId">EmpId:</label>
   <input id="empId" data-dojo-type="dijit/formTextBox"         
   type="text"/>
   </td></tr><tr><td>
   <button data-dojo-type="dijit/form/Button" id="buttonId"   onclick="getWelcomeJsp();">Send</button>
   </td></tr></table>
   <div id="loadResponse"></div>
   </body></html>

Welcome.jsp:-

   <!DOCTYPE html>
   <html><head>
   <style type="text/css>"
      @import "../Script/dojo-1.10/dijit/themes/claro  /claro.css";</style> 
   <script type="text/javascript"  lang="JavaScript"          src="../Script/dojo-1.10/dojo/dojo.js">   </script>
    <script type="text/javascript"  lang="JavaScript">
    require(["dojo/parser","dojo/ready"],function(parser,ready){
    dojo.ready(function(){
        parser.parse();
        alert("From Ready");
    });
    });
   function myfunction(){
        alert("from welcomedd JSP");
   }
   </script></head>
   <body class="claro" onload="myfunction();">
   This Is Welcome JSP
   <button id="responseButton" data-dojo-type="dijit/form /Button" onclick="myfunction();">Response Button</button>
   </body></html>

When clicking on the hyperlink in Home.jsp using dojo 1.9 version, Thank you". The issue arises when attempting to load the Welcome.jsp through an ajax call from Home.jsp.

The problem is that while Welcome.jsp gets loaded through ajax, the ready function and onload function within Welcome.jsp are not being called. Any solutions or insights into this issue would be greatly appreciated.

Answer №1

For security reasons, when adding scripts using AJAX and setting the content as inner HTML, they are not evaluated by the web browser.

To work around this limitation, there are a few options available:

  1. If you only need certain widgets to load, you can utilize the dijit/layout/ContentPane widget and specify the href property. This will fetch the content through AJAX and automatically parse all widgets.

  2. If your goal is to execute scripts on the page, you must use eval(). Refer to this answer for more information: Can scripts be inserted with innerHTML?
    This entails iterating through all scripts within the dynamic content and applying eval() to each.

  3. A simpler approach to executing script on the page and parsing all widgets simultaneously is to explore the dojox/layout/ContentPane module. It functions similarly to the dijit/layout/ContentPane module but includes an additional property called executeScripts, which allows you to evaluate scripts on the page. For example:

<div id="loadResponse" data-dojo-type="dojox/layout/ContentPane"
    data-dojo-props="href: 'welcome.jsp', executeScripts: true"></div>

Answer №2

There is an alternative solution that I came up with for resolving this issue.

  1. To start, remove all script and CSS-related code from the welcome.jsp file, as well as from within the body tags.
  2. Within the getWelcomeJsp() function, after setting the data to the div using innerHTML, invoke parser.parse(); and list out all components utilized in welcome.jsp under require.

If you need to trigger any event such as keyup or click, you can utilize the following code snippet:

on(domNode,"click",function(event){
//implementation logic
}); 

Add this code below the parser.parse(); line.

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

Preview of Live Iframe Display

Currently, I am in the process of developing a node.js website that enables users to create and customize their own page using a dashboard interface. One specific feature I would like to incorporate is a live preview capability, similar to what Shopify o ...

Confirm the contents of a form retrieved through ajax

Let me explain the issue I am facing. I have created an HTML page with a simple form and some jQuery code for validation. This is how the page looks: <html> <head> <title></title> <script src="jquery-1.7.min.js" type="text/jav ...

Using AJAX POST for real-time validation of usernames and email addresses

Creating a basic form with AJAX and jQuery to validate the username and email address before submitting: <body> <div> <h5> Registration </h5> <hr /> <div> Username: <input type="text" size="32" name="membername" ...

I designed my higher-order component to allow for dual invocations. How can I integrate Redux within this framework?

I have implemented my higher-order component (HOC) in such a way that it can be invoked twice, emphasizing the concept of "functional programming". However, I am facing challenges in connecting Redux to access state and certain functions. I would greatly ...

The option tag value was not accurately captured

This piece of code is used to select subjects within a course. The HTML code for this functionality is as follows: <form action="mode" onSubmit="calcRoute();return false;" id="keywordForm"> <table bor ...

What could be causing the JSON String decode error to occur while utilizing extjs ajax?

Here is an example of my code: Ext.Ajax.request({ url:'test.jsp', params:{id:id,password:password}, success:function(response){ console.log(response); var results = Ext.util.J ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Use either lodash or a for loop to organize a group of JSON objects

Here is the array I am working with: [ { corequisite: "", curriculumYr: "2017-2018", programCode: "ET" majorCode: "AET", prerequisites: "GMRC 101||Math 101" semester: "1st Term", year: "1st Year", subjectCode : "ENG ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Preventing Click Event Propagation in React Using e.stopPropagation()

I am facing an issue with a div wrapped in a Link tag within NextJS. Inside this div, there is a row of button components. Whenever I click on a button, it performs its action correctly but also triggers the Link tag from the parent div causing us to navig ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

Using observables rather than promises with async/await

I have a function that returns a promise and utilizes the async/await feature within a loop. async getFilteredGuaranteesByPermissions(): Promise<GuaranteesMetaData[]> { const result = []; for (const guarantees of this.guaranteesMetaData) { ...

Utilizing Vue.js to share a single array of data across two distinct input lists

For a clearer understanding of my requirements, I have put together a demo on JSFiddle: https://jsfiddle.net/silentway/aro5kq7u/3/ The code snippet is presented below: <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id=" ...

randomly create a value that is not already included in the

I need help creating a random number that is not included in a specific array of numbers. JavaScript Solution: var restricted = [3, 4, 7]; function getRand () { rand = Math.floor(Math.random() * 10); if ($.inArray(rand, restricted) === -1) { ...

Locate a specific document by searching for a specific value within a subdocument contained within an array

In my database, there exists a Mongoose collection named WorkoutUser with a simplistic schema as shown below: const WorkoutUserSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User', required: true, }, exercises: ...

Encountering a CORS issue while making a fetch request in ReactJS's componentDidMount lifecycle method

When trying to fetch API data in ReactJS, I am getting an empty page as output. Repository: https://github.com/te3t0/building-small-blog I am relatively new to ReactJS and encountering issues where the page remains empty even after successfully fetching ...

Tips for re-matching the initial word or putting the initial word in parentheses at the start

When the string is "find().nodes() as n3" it will be interpreted as 'find' But when the string is "with n1,n2,n3" it will be understood as 'with' ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

Is there a way to implement an X icon in Material UI Modals to close them instead of relying on clicking outside the modal?

In my React app, I am utilizing the Material UI Modal component which occupies around 95% of the screen. To improve user experience, I want to include a small "X" icon in the upper right corner of the modal for closing it. Although I am passing down the sa ...

Manage and preserve your node.js/express sessions with this offer

Currently, I am working on a web application that encounters an issue where every time fs.mkdir is called, all the current express sessions are deleted. This causes me to lose all session data and I need a solution to keep these sessions intact. I have att ...