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'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

What is the best way to use ajax with jquery for file uploading?

Is it possible to use jQuery and ajax to upload an image with this code or something similar? jQuery.ajax({ type: "GET", url: "/userinfo/update/", dataType: "json", data: { ...

Encountering error #426 in NextJs when the app is loaded for the first time in a new browser, but only in a

Encountering a strange error exclusively in production, particularly when loading the site for the first time on a new browser or after clearing all caches. The website is built using nextjs 13.2.3 and hosted on Vercel. Refer to the screenshot below: http ...

What is the best method for importing several components from a directory in ReactJS?

I'm looking for a way to import multiple React components from a directory without having to export them separately in an index.js file. Here's the structure of my directory: src/ components/ comp1.js comp2.js comp3.js ...

JQuery ajax DELETE request encounters issues during the OPTIONS stage

I'm encountering an issue while trying to send a delete request using JQuery as it consistently results in a 500 internal server error. Here's the code snippet I'm using for the request: $('#deleteReview').click(function(event, ui ...

Designate the forward slash as the URL path

Can Express handle requests like this? app.get('/.test/abc', function(req, res) { res.send( 'abc test' ) }) So if I visit localhost:3000/.test/abc, it should display abc test. I tried it but it seems to not be working. Do I need t ...

The Bootstrap 3.3 Carousel is stationary and does not rotate

I am facing a challenge with implementing a Carousel using Bootstrap version 3.3.7 on my website. The code snippet is as follows: <!-- Carousel ================================================== --> <div class="row dark-start d-none d-lg-block"&g ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

Choosing Between Methods and Computed Properties in Vue.js

Can you explain the primary distinction between a method and a computed property in Vue.js? I'm finding it tricky to differentiate between the two as they appear quite similar. ...

The sendKeys() method is malfunctioning in Selenium WebDriver

When attempting to enter phone numbers into the designated field, an error is being encountered. Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element The following code snippet is involved: driver.get("https://m ...

Utilizing nested HTML within an HTML tag

Recently, I've been exploring the concept of nested HTML in Bootstrap. While following a tutorial on using Popovers, I encountered the following code; <button id="btn3" type="button" class="btn btn-primary show" ...

Can you notify all channels when the discord bot experiences a crash?

Is there a way to have my discord bot send a message in a specific channel when it crashes, similar to what I've seen with other bots? ...

From JSON to HTML: the beauty of nesting

I believe there might be a foolish error lurking in my code, waiting to be uncovered. I am working with JSON data sourced from an external site at . The goal here is to extract specific data elements, such as stationShortCode, type, commercialTrack, and s ...

What is preventing me from using GET to pass parameters to WebMethod?

Here is an example of how my WebMethod is structured: [WebMethod] [ScriptMethod(ResponseFormat=ResponseFormat.Json, UseHttpGet=true)] public List<Person> Greetings(string greeting) { List<Person> individuals = new List<Person> { ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format: queryObj = {}; // main object passed to mongodb for queries The code snippet below is causing an error: queryObj[inObj.row]['$ ...

Using an imported material icon as a background in JSS styling

I have implemented a draggable dialog component in React-mui with a resizable box feature. const styles = theme => ({ resizable: { position: "relative", "& .react-resizable-handle": { position: "absolute" ...