I'm calling serialize on a form during the submit event, so that I can get the form inputs and then prevent submission. I checked that all the inputs have name values and aren't disabled before submitting, but .serialize still returns an empty string. Any help would be appreciated, thank you!
The HTML for my code is here
div(class='waitlist' id='waitlist')
h1(id='waitlisttext') Add me to the waitlist
form(action="" id='waitlistform')
// target="_blank" method="POST" action="../waitlistdata.php"//
label(for="fname") First name:
br
input(type="text", id="fname", name="fname", value="" required)
br
label(for="lname") Last name:
br
input(type="text", id="lname", name="lname", value="" required)
br
label(for="email") Email:
br
input(type="text" id="email" name="email" value="" required)
br
br
input(type="submit" name="submit" value="Submit")
The JS for my submit function is here, with a check that the input isn't disabled before calling serialize, and an alert that returns the serialized string.
$("#waitlist").on("submit", function(e) {
console.log('submit function called')
console.log(document.getElementById('fname').disabled)
var dataString = $(this).serialize();
alert(dataString); return false;
$.ajax({
type: "POST",
url: "../views/waitlistdata.php",
data: dataString,
success: function () {
$("#waitlisttext").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
return false;
});
Putting aside for a moment that this is not HTML, and assuming it's some other language which produces logically similar HTML...
You're not serializing the <form>
, you're serializing the <div>
. This event handler:
$("#waitlist").on("submit", function(e) {
Is binding to this element:
div(class='waitlist' id='waitlist')
So this is trying to serialize that element:
var dataString = $(this).serialize();
Perhaps you meant to bind the event to the <form>
instead:
$("#waitlistform").on("submit", function(e) {
Alternatively, if you still want to bind the event handler to the <div>
then you'd have to select the <form>
to serialize it:
var dataString = $(this).find("form").serialize();