[javascript] Capturing a form submit with jquery and .submit

I'm attempting to use jQuery to capture a submit event and then send the form elements formatted as JSON to a PHP page. I'm having issues capturing the submit though, I started with a .click() event but moved to the .submit() one instead.

I now have the following trimmed down code.

HTML

<form method="POST" id="login_form">
    <label>Username:</label>
    <input type="text" name="username" id="username"/>
    <label>Password:</label>
    <input type="password" name="password" id="password"/>
    <input type="submit" value="Submit" name="submit" class="submit" id="submit" />
</form>

Javascript

$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
});

This question is related to javascript html jquery

The answer is


_x000D_
_x000D_
$(document).ready(function () {_x000D_
  var form = $('#login_form')[0];_x000D_
  form.onsubmit = function(e){_x000D_
  var data = $("#login_form :input").serializeArray();_x000D_
  console.log(data);_x000D_
  $.ajax({_x000D_
  url: "the url to post",_x000D_
  data: data,_x000D_
  processData: false,_x000D_
  contentType: false,_x000D_
  type: 'POST',_x000D_
  success: function(data){_x000D_
    alert(data);_x000D_
  },_x000D_
  error: function(xhrRequest, status, error) {_x000D_
    alert(JSON.stringify(xhrRequest));_x000D_
  }_x000D_
});_x000D_
    return false;_x000D_
  }_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="POST" id="login_form">_x000D_
    <label>Username:</label>_x000D_
    <input type="text" name="username" id="username"/>_x000D_
    <label>Password:</label>_x000D_
    <input type="password" name="password" id="password"/>_x000D_
    <input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


Just replace the form.submit function with your own implementation:

var form = document.getElementById('form');
var formSubmit = form.submit; //save reference to original submit function

form.onsubmit = function(e)
{
    formHandler();
    return false;
};

var formHandler = form.submit = function()
{
    alert('hi there');
    formSubmit(); //optionally submit the form
};

try this:

Use ´return false´ for to cut the flow of the event:

$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

Edit

corroborate if the form element with the 'length' of jQuery:

alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

OR:

it waits for the DOM is ready:

jQuery(function() {

    alert($('#login_form').length) // if is == 0, not found form
    $('#login_form').submit(function() {
        var data = $("#login_form :input").serializeArray();
        alert('Handler for .submit() called.');
        return false;  // <- cancel event
    });

});

Do you put your code inside the event "ready" the document or after the DOM is ready?


Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?