Is there a way to trigger a function within the submit handler with jQuery validation?

I've been attempting to trigger an ajax function once the form is validated, but I'm running into some issues. The jQuery on-submit method below is working perfectly for me.

$('#promotionAdd').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        promotionAdd(formData);
        return false;
    }));

However, I'm trying to achieve the same thing in the submitHandler which isn't working for me.

$(document).ready(function () {
        $('#promotionAdd').validate({ // initialize the plugin
            rules: {
                mtitle: {
                    required: true,
                    minlength: 3, 
                }
            },
            messages: {
                mtitle: "Please enter Promotion Title",
            },
            submitHandler: function (form) { // for demo
                //alert(this);
                e.preventDefault();
                var formData = new FormData(this);
                promotionAdd(formData);
                return false;
            }
        });
    });

If anyone can provide guidance on where I might be going wrong and how to fix it, I would greatly appreciate it. Thank you!

Answer №1

When working with the submitHandler, remember that this refers to the validation plugin and not the form itself. Instead, make use of the form parameter passed into the function.

It's worth noting that using preventDefault() without defining

e</code will result in an error, and <code>return false
won't have any effect. In this scenario, these are unnecessary as the validation plugin handles form submission prevention for you automatically. Here's a revised approach:

submitHandler: function (form) {
    var formData = new FormData(form); // Use 'form' in place of 'this'
    promotionAdd(formData);
}

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

The app is not showing the Post Request message after it has been sent from the UI front end

I am currently developing a chat application using node.js, express.js, socket.io, and mongodb. However, I have encountered an issue during the Node.js and express.js implementation (socket.io and mongodb are not yet utilized). The problem is that the code ...

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

Utilizing the power of jQuery to efficiently manage HTML5 audio playback on your web page

I have created a unique tour experience on my website that utilizes HTML5 animation. The tour incorporates sound using the HTML5 audio tag and is loaded into the page with jquery. Once the tour is loaded, it automatically starts playing the audio. However ...

Dynamic parallax or stacked vertical text animation

I am attempting to replicate the text effect found on . The text is centered both vertically and horizontally within each div, but as you scroll down, the top position shifts creating a parallax effect. As you continue scrolling, the text transitions to th ...

Comparing the Distinctions of jQuery Post and HTML Form Post

After researching extensively, I am still confused about the difference between a Jquery $.post method and submitting an HTML form using post. Here is my code for the jQuery implementation: $.post( "/test", query , function( data ) { console.log(data) ...

Retrieving data from a separate server using GWT on the client side

My dilemma involves a file called sample.xml residing on one web server, and I need to retrieve this file from a GWT application running on a separate server. Rather than making RPC calls to the GWT server to access the file through server-side proxy, I pr ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

It is not possible for $_GET to loop through an array

I have a list of values called dataId obtained from checkbox selections, and I want to send it via a GET AJAX request: dataId = 1, 2, 16, 15, 17, 3, 14, 5, 9, 11; URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>"; $. ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

Extracting the input's data and placing it into a table cell

Hey there! I am facing an issue where the data entered in the input fields is not getting transferred to the respective <td>. The text displayed in the (tabios) field should change according to what is entered in the input. Here's the code snipp ...

Accessing an array outside of an Ajax call that was initiated within a success callback

I have a CSV parsing function written in JavaScript that extracts movie names from a CSV file using an Ajax call within a loop. movies = new Array(); for (var i = 1; i < allData.length; i++) { var mName = allData[i][0]; var mPath = allData[i ...

Create an Ajax request function to execute a PHP function, for those just starting out

I came across a JS-Jquery file that almost meets my needs. It currently calls a PHP function when a checkbox is clicked, and now I want to add another checkbox that will call a different PHP function. My initial attempt was to copy the existing function a ...

Is it possible to load a Twitter widget from dynamically loaded HTML using AJAX?

I've been attempting to implement a standard Twitter search widget directly from the Twitter website: <script src="http://widgets.twimg.com/j/2/widget.js"></script> <script> new TWTR.Widget({ version: 2, type: 'search' ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

Tips for setting up my ajax/views method to output a dictionary

Here's the HTML snippet I have along with an AJAX request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"end ...

Codeigniter session unexpectedly ends after AJAX call completes successfully

Currently, I am utilizing the CodeIgniter framework on a Heroku server with an AWS database. In my AJAX success function, I have a window.location.reload(); call which ends up destroying the session and redirecting to the login page. Is there a way to prev ...

Tips for displaying all 'ul li' lists in media queries to ensure responsiveness in design

When I view my navigation bar snippet on desktop mode, it displays all the list items. However, when I adjust the browser width to fit my media queries, only the Home list is shown in the nav bar. Here's an example of the issue: Before Clicking the ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...