64

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.');
});
Alexis Tyler
  • 1,394
  • 6
  • 30
  • 48
Nathan
  • 2,461
  • 4
  • 37
  • 48
  • 4
    How about sticking an `event.preventDefault()` in there to start with ? – adeneo Sep 03 '12 at 18:10
  • i have no idea what that means or where to place it, sorry i am pretty new to jquery. – Nathan Sep 03 '12 at 18:14
  • You have to prevent the default action of the submit, otherwise the form will be submitted and the page will reload, and nothing will work as it should. You do that with [event.preventDefault()](http://api.jquery.com/event.preventDefault/) <- Link to docs ? – adeneo Sep 03 '12 at 18:17
  • 1
    And you did of course include the jQuery library and wrap your code in document.ready ? – adeneo Sep 03 '12 at 18:20
  • aha, that was it. i hadn't put it in a document.ready. I was looking at the examples in the docs and they don't include it. Oh well, something new learnt! Thanks for your help. If you want to put it in an answer i'll mark it as correct. – Nathan Sep 03 '12 at 18:24
  • You should use serializeArray on the form tag http://api.jquery.com/serializeArray/ – Shikyo Sep 03 '12 at 18:32
  • Any jQuery object representing a set of form elements can be passed to serializeArray(), also just the inputs. – adeneo Sep 03 '12 at 18:34
  • can you change the submit button to a regular button, and use javascript to call your function? – ajon Sep 03 '12 at 18:12

5 Answers5

167

Wrap the code in document ready and prevent the default submit action:

$(function() { //shorthand document.ready function
    $('#login_form').on('submit', function(e) { //use on if jQuery 1.7+
        e.preventDefault();  //prevent form from submitting
        var data = $("#login_form :input").serializeArray();
        console.log(data); //use the console for debugging, F12 in Chrome, not alerts
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Just to add more specfication, the `e.preventDefault()` is very important because, without it, the form will submit using the action attribute of the form and wil also call your code. With the preventDefault, you'll be able to override the normal behavior of a HTML form – RPDeshaies May 08 '14 at 15:50
16

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?

andres descalzo
  • 14,887
  • 13
  • 64
  • 115
7

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
};
craigrs84
  • 3,048
  • 1
  • 27
  • 34
2

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

Marcelo Agimóvel
  • 1,668
  • 2
  • 20
  • 25
0

$(document).ready(function () {
  var form = $('#login_form')[0];
  form.onsubmit = function(e){
  var data = $("#login_form :input").serializeArray();
  console.log(data);
  $.ajax({
  url: "the url to post",
  data: data,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  },
  error: function(xhrRequest, status, error) {
    alert(JSON.stringify(xhrRequest));
  }
});
    return false;
  }
});
<!DOCTYPE html>
<html>
<head>
<title>Capturing sumit action</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<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>

</body>

</html>
Welisson Moura
  • 321
  • 1
  • 2