Using the Dojo framework, make an Ajax request within a Yes No Dialog box

In order to fulfill a requirement, I need to initiate an ajax call to a controller when the Yes button is clicked within a Dojo Dialog Box. The Dojo dialog box is created through JavaScript and triggered by clicking a button in a JSP file.

Here is the code for the Dojo Dialog Box:

function launchYesNoDialog(message, action) {
    require(["dijit/Dialog", "dojo/domReady!"], function(Dialog){
        yesNoDialog = new Dialog({
            title: "Warning",
            content: message+'<BR><BR><BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
            ' <button data-dojo-type="dijit/form/Button" id="yesButton">Yes</button>'+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
            '<button data-dojo-type="dijit/form/Button" id="noButton" data-dojo-props="onClick:function(){yesNoDialog.hide();}">No</button>'
        });
    });
    yesNoDialog.show();
}

This is the code snippet from the JSP file that triggers the Dojo dialog:

<button type="button" id="removeCustomerButton"
                                 style="float: left;"
                                disabled="disabled" onclick="launchYesNoDialog(confirmMessage,'Remove');">
                                <SPAN class=grey><EM><s:message
                                            code="customer.removeCustomer" text="" /></EM></SPAN>
                            </button>

Below is the Ajax code where the ajax functionality is implemented:

require(["dojo/request/xhr", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/_base/lang", "dojo/domReady!"],
        function(xhr, dom, domConst, JSON, on, lang){
          on(document.getElementById("yesButton"), "click", function(){
              var val = selectedId;
              if(lang.trim(val).length == 0){
                  return;
              }
              waitingForResponse();
            xhr("relationship/deleteCustomer/"+val, {
              handleAs: "json"
            }).then(function(data){
                waitingEnd();
                buildDataGrid("relationGrid", data, null, 0, 'A');
            },  function(err){
                waitingEnd();
            });
    });
});

Upon loading the page, there is a "Null Object error" being thrown by JavaScript due to this line of code:

(document.getElementById("yesButton"), "click", function()

It seems like JavaScript is trying to locate the Yes Button before it's even rendered in the DOM. Can anyone suggest a solution to this issue?

Answer №1

When utilizing a dijit widget, it is vital to obtain a reference of the dijit object by using the dijit/registry module.

Furthermore, it is necessary to parse the HTML contents in the dialog box in order to transform the yes/no buttons into dijits.

function createYesNoDialog(message, action) {
    require(["dijit/Dialog", "dojo/parse", "dojo/domReady!"], function(parse, Dialog){
        yesNoDialog = new Dialog({
            title: "Alert",
            content: message + '<BR><BR><BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
            ' <button data-dojo-type="dijit/form/Button" id="yesButton">Yes</button>'+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
            '<button data-dojo-type="dijit/form/Button" id="noButton" data-dojo-props="onClick:function(){yesNoDialog.hide();}">No</button>'
        });
        parser.parse(yesNoDialog.content);
    });

    yesNoDialog.show();
}

Add the dijit/registry module to the require statement.

require(["dojo/request/xhr", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/_base/lang", "dijit/registry", "dojo/domReady!"],
        function(xhr, dom, domConst, JSON, on, registry, lang){
          //on(document.getElementById("yesButton"), "click", function(){
          registry.byId("yesButton").on("click", function(){
          .... 

If the above method still does not yield results, you can develop your own confirmation dialog widget by referring to this example on jsfiddle.

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

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

Dealing with Errors in jQuery AJAX WebMethods

Struggling to access the object returned from a webmethod in my jQuery Ajax method. Trying to display HighlightResults in a repeater but keep encountering an error: Internal server error. The object in question: public class SearchResults { inter ...

upload document to joomla

Hello, I am currently working with Joomla and I am attempting to provide users with the option to download a CSV or Excel file of the table they are currently viewing. I have been using PHPExcel for the file creation process. Here is the content of my exp ...

My dispatch isn't functioning properly - what's wrong with it? React Redux

I'm attempting to update my firebase username using the redux store. Within a registration form, I collect the email, password, and desired username input. Once the form is submitted, a firebase account is created with the email and password, followe ...

Saving an incremented number using Vue JS in Firebase database

I have a VueJS app integrated with Firebase JSON database where I'm trying to implement a feature that allows users to update the vote count of a comment by clicking an arrow (similar to upvotes on this website). The function works properly, but the V ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

Having trouble with Bootstrap's "hidden-xs" class not working and struggling to create a sticky footer for small viewports

Trying to tackle the challenge of making my footer stick to the bottom of the page on smaller screens has been quite troublesome. As a temporary fix, I decided to experiment with hiding the div entirely until I figure out a proper solution. The HTML < ...

What causes the failure of this select menu in the latest combination of jQuery and JQM?

I am looking to enhance this code, but I have noticed that it does not limit the selection (by count) in the newer versions of jQuery and JQM. Check out this example which demonstrates that it works with jQuery 1.8.3 and JQM 1.2.0. Here is the jQuery cod ...

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...

Can stringByEvaluatingJavaScriptFromString be utilized with JavaScript that makes references to local files?

     I am looking to implement stringByEvaluatingJavaScriptFromString in order to execute a JavaScript code that accesses local files (such as CSS or JS files) stored on the device (presumably in the Documents folder)... NSString *theJS = [[NSString ...

A guide on implementing a loop in a JSON to XML plugin

I've recently started using the 'jstoxml' plugin developed by the talented David Calhoun. If you're interested, here is the link: https://github.com/davidcalhoun/jstoxml The challenge I'm facing is related to my goal object. I ne ...

Troubles with Express JS POST Requests

I'm facing an issue while attempting to write code that creates a MongoDB entry using express.js. Every time I test my code with a cURL request, I receive an error message stating "empty response from server". Below is the snippet of my express.js co ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

json undefined result or results when viewing in MVC

After passing the LINQ result to my dropdown list, I am seeing "undefined" displayed. The issue could be because I didn't specify a specific class after "select new," although that is how I need it. var newlist_of_device_types = (from z in DB.t_d ...

Creating a form that displays only three questions simultaneously

My survey form consists of 13 questions, all displayed on one page. However, I would like to only show 3 questions at a time and then have the next set of 3 questions appear on the following page. I am not sure how to accomplish this. Any assistance would ...

Tips for optimizing character count for mobile web pages with varying screen sizes and font settings

As I embark on developing an eBook mobile app, I am faced with various considerations such as screen size, font size, and determining the number of paragraphs to include on a single page based on the current screen and font settings. My aim is to adjust t ...

The NPM package manager is unable to locate jquery.js and jquery.keyframes.js

I've encountered an issue while working with jquery and jquery.keyframes. My project structure involves storing NPM js files in the node_modules folder and html files in the public folder. However, when I use the following code, the html file is unabl ...

What is the best way to perform an action in the database using JavaScript without needing to refresh the page

I have written a code that retrieves data from a table, with each row containing two buttons for updating the database with a fixed value and deleting the row. I am looking to perform these actions without reloading the page. Below is the table code: &l ...

Managing document field permissions in a Meteor application: Best practices for restricting which fields can be inserted or updated

I am currently using Meteor and I have some concerns regarding security vulnerabilities. My main goal is to restrict users from creating or modifying certain fields in the database. Specifically, I only want users to be able to add or update the name and d ...

How come the date is not showing up inside the <p> tag?

Check out this snippet of HTML code: <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="bootstrap_4.5.0&bsol ...