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.'); });
jQuery submit() Method The submit event occurs when a form is submitted. This event can only be used on <form> elements. The submit() method triggers the submit event, or attaches a function to run when a submit event occurs.
$("#something-%"). submit(function(e) { e. preventDefault(); $("#some-span"). html(data); });
The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data. Parameter: It does not accept any parameter.
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 }); });
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With