What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet:

<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConfig="parseOnLoad: true"></script>
<script type="text/javascript">
            dojo.require("dijit.form.Form");
            dojo.require("dijit.form.Button");
            dojo.require("dijit.form.ValidationTextBox");
    </script>
    <script>

    function send()
    {
        var mainForm = dojo.byId("mainform");
        dojo.connect(mainForm, "onsubmit", function(event)
        {
            dojo.stopEvent(event);
            if (mainForm.validate())
            {
                alert("valid");
                var xhrArgs = {
                        form: dojo.byId("mainform"),
                        load: function(data)
                        {
                            // Success
                            alert("Success");
                        },
                        error: function(error)
                        {
                            // Error
                            alert("Error");
                        }
                    }
                var deferred = dojo.xhrPost(xhrArgs);
            }
            else
            {
                alert("not valid");
            }
            });
    }
    dojo.addOnLoad(send);
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css"/>
</head>
<body class="claro">
    <h2>Invitation:</h2>
    <div dojoType="dijit.form.Form" id="mainform" jsId="mainform" encType="multipart/form-data" action="whatever.php" method="post">
        <label for="name">Name:</label><input type="text" id="name" name="name" size="50"
                    dojoType="dijit.form.ValidationTextBox"
                    required="true"
                    propercase="true"/>
                    <br><br>

        <button type="submit" dojoType="dijit.form.Button">Send Message</button>
    </div>
</body>

In the actual production code, I do not utilize "alert" messages; they simply assist me in determining what aspects are functioning correctly and what might require adjustments. The issue at hand here is that the call to mainForm.validate() seems to get stuck and does not return. By eliminating this validation call, the form data successfully gets posted to the .php file, however, there is no validation procedure in place.

Answer №1

Welcome to our community on StackOverflow!

Remember to always use dijit.byId when searching for dijits instead of just their DOM nodes with dojo.byId. Also, make sure you are using correctly capitalized event names. Consider modifying your send function in the following way:

function send()
{
    var mainForm = dijit.byId("mainform");
    dojo.connect(mainForm , "onSubmit", function(event)
    ....

Using dojo.byId will return a regular DOM node (like an ordinary HTML <form> tag) instead of the actual dijit object with functions like validate. That's why using incorrectly cased "onsubmit" may still work: a standard HTML form has an event named "onsubmit", while the dijit uses a method called "onSubmit" (though it can be confusing).

Answer №2

Imagine a delicious pie cake. Follow these steps to make it happen. The dijit.form.Form object has an attribute called state. If this state is an empty string, then form widgets like the dojo textbox are considered valid.

Here's how you can achieve this: 1) Avoid attaching onsubmit for the form. Instead, just attach a click event for the button and include the following code inside the button click handler.

var validForm = "";
dojo.connect( submitBtnDojoWidget, "onclick", function( event ){
 if(mainform.state === validForm){
  mainform.submit();
 }
 else {
  // In this case, mainform.state could be 'invalid' or 'incomplete'
  console.log(mainform.state);
 }
})

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

I am looking to update the background color of the material UI helper text

In the image below, you can see that my background color is gray and my text field color is white. When an error is shown, the text field's white color extends and the password error message doesn't look good. I want the text field to remain whit ...

Unable to modify the value of data using the data() method

Just a basic HTML code snippet <div class="this" data-info="false"></div> $('.this').data('info'); This will correctly output: false $('.this').data('info', 'true'); data-info remains u ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

Transform an SVG string into an image source

Is there a way to convert an incoming string ' ' into an img src attribute and then pass it as a prop to a child component? I attempted the following method, but it hasn't been successful. `let blob = new Blob([data.payload], {type: &apos ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

Unexpected TypeScript issue: Unable to access the 'flags' property of an undefined entity

Upon creating a new project and running the serve command, I encountered the following error: ERROR in TypeError: Cannot read property 'flags' of undefined Node version: 12.14 NPM version: 6.13 Contents of package.json: { "name": "angular-t ...

Choose the specific Element by its dynamicID in JQuery

Just starting out with Jquery and I have a specific task in mind. In my HTML page, I have elements with IDs generated by concatenating a string variable. My goal is to use JQuery to select the element with this dynamically generated ID. See below for more ...

Ways to resolve the angular error "Encountering an unhandled exception: Unable to locate module 'typescript' "?

I'm encountering errors when running ng serve. I've attempted the following code as well, but I'm still facing the same error: npm install -g typescript Error displayed in text format D:\xampp\htdocs\angular\axen>ng ...

JavaScript Bug Report

Currently, I am immersed in a project that encompasses various languages like HTML, JS, and PHP. While working on one of the PHP functions, I stumbled upon an unexpected anomaly. To dissect it better, I decided to break it down into simpler functions: &l ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

The Azure SpeechSynthesizer encountered an error due to using HTTP instead of the expected HTTPS protocol. This issue can be resolved by installing the NPM package `microsoft

Recently, I have been encountering an issue with the microsoft-congnitiveservices-speech-sdk npm package. Everything was working smoothly until randomly an error started popping up. This could be due to a browser update or a minor package update - I'm ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

What is a workaround for sending a large/multi-part JSON object without adjusting the maxJsonLength setting?

I'm facing an issue in my C# web application where I receive a JSON object from a WebMethod and it exceeds the maximumJSONLength, resulting in: InvalidOperationException: The length of the string exceeds the value set on the maxJsonLength property. ...

Saving URLSearchParams to a file using javascript

I am currently implementing jstree and I need to be able to click on a file within the tree structure in order to display a PDF file. Below is the relevant code snippet: $(function () { $('#tree').jstree({ 'core' : { ...

Leveraging AJAX for fetching data from a deeply nested JSON structure

My AJAX request is functioning properly: $.ajax ({ url: 'api.php', type: 'GET', data: {search_term: data}, dataType: 'JSON', success: function(data) { $('#div').html('<p>Consti ...

dimming of dojo dijit.Dialog

I've been encountering issues with "undimming" a Dojo Dijit dialog. Even though I am using the appropriate calls, there are instances where parts of the page remain dimmed. I can still scroll through the windows and access the undimmed sections. Is th ...

Instant access to an interactive online platform

Is it feasible to create a shortcut from a webpage to my desktop for quick access? For instance, if a dynamic web page has 15 documents and I want to easily create shortcuts to them on my desktop by clicking on each one. I understand this is a brief quest ...

Is there a better method to accomplish this task in a more effective manner?

Is there a more efficient way to achieve this code with fewer lines of code? I'm looking for a solution that avoids repetition and makes it easier to manage, especially since I plan on creating multiple instances of this. Performance is a key consider ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...

Using a global variable to change the class of the <body> element in AngularJS

I've recently developed an angularJS application. Below is the index.html <html ng-app="MyApp"> <head> <!-- Import CSS files --> </head> <body class="{{bodylayout}}"> <div ng-view></div> < ...