Capturing a form submit with jquery and .submit - javascript

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.');
});

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?

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
};

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

$(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>

Related

How to submit single form via AJAX when you have multiple forms from PHP loop

I am trying to submit a form on keyup, sort of a keylogger effect. Here is my attempt -
php loop form -
<form method="post" id="'.$vid.'" class="note-form">
<textarea id="'.$vid.'" name="quicknote" value="'.$quick_note.'" placeholder="add a quick note" class="quicknote">'.$quick_note.'</textarea>
<input type="hidden" name="tac" value="'.$vid.'"/>
</form>
$vid is the unique id for each form that im passing from the DB.
JS file -
// Capture keyup from textarea to submit form
$('.quicknote').bind('keyup', function() {
var id = this.id;
var formID = "#"+id;
$(formID).delay(200).submit();
});
$(formID).submit(function(e) {
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
I use the same ID for the form and the inputs but the form isnt submitting. I can submit if I use the form class note-form but it submits all forms. I cant make formID a global variable to pass to the ajax function also. What is the correct way to do this?
Your form id and textarea id are same that's why its causing problem . Instead you can use
$(this).closest('form') this will get closest form from textarea then you can submit only that form.
Demo Code :
$('.quicknote').bind('keyup', function() {
var selector = $(this).closest('form') //get closest form
$(selector).delay(200).submit(); //submit that.
});
$("form").submit(function(e) {
console.log("data to send --> " + $(this).serialize())
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="note-form">
<textarea id="1" name="quicknote" value="somethings..." placeholder="add a quick note" class="quicknote">somethings..</textarea>
<input type="hidden" name="tac" value="1" />
</form>
<form method="post" class="note-form">
<textarea id="2" name="quicknote" value="somethings" placeholder="add a quick note" class="quicknote">somethings...</textarea>
<input type="hidden" name="tac" value="2" />
</form>

Jquery not functioning properly in Google Apps Script

I have this code:
index.html
<!DOCTYPE html>
<html>
<div>
<form id="email_subscribe">
<input type="email" name="email" id="email" placeholder="Enter your email">
<input type="submit" value="Subscribe">
</form>
<span id="thank_you" hidden="true">Thank you!</span>
</div>
<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$( "#email_subscribe" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
$("#email_subscribe").slideUp();
$( "#thank_you" ).show("slow");
console.log(ret);
}).addEmail(this); //"this" is the form element
});
});
</script>
</html>
and this one:
Code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle("Web App 2").setSandboxMode(HtmlService.SandboxMode.NATIVE);
return html;
}
function addEmail(form){
Logger.log(form.email);
return 200;
}
The "Thank you message" is not showing up upon submitting the form. Can you please tell me what am I doing wrong. Thank you.
With IFRAME mode however HTML forms are allowed to submit, and if a
form element has no action attribute specified it will submit to a
blank page.
— Offical Documentation
The solution is to add a return false; or event.preventDefault() at the end of your submit function to tell the browser to cancel the event, your code should look like this:
$( "#email_subscribe" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
$("#email_subscribe").slideUp();
$( "#thank_you" ).show("slow");
console.log(ret);
}).addEmail(this); //"this" is the form element
return false;
});
You can also implement the solution suggested in the docs, create an EventListener to prevent all form submitions on load with this code:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>

Why isn't the form submitting after validation

HTML:
<form method="post" name="contact" id="frmContact" action="smail.php">
...
<label for="security" class="smallPercPadTop">Please enter the result:</label> <br /><h3 id="fNum" class="spnSecurity"></h3><h3 id="nCalcType" class="spnSecurity"></h3><h3 id="sNum" class="spnSecurity"></h3> = <input type="text" placeholder="Enter the result" name="security" id="security" class="required input_field_custom" />
<br /><br />
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
<input type="reset" value="Reset" id="reset" name="reset" class="submit_btn" />
</form>
Script:
$('form').on('submit', function(e) {
e.preventDefault();
var vGetResult = $("#security").val();
if (vGetResult == vResult) { //""vResult"" is a value that I set when the page loads...
alert("good");
$("#frmContact").submit();
}
});
What I am trying to do is, once I validate what the user entered is the same as another number then I would like to submit the form. Instead of submitting the form, I keep getting the alert statement infinitely.
How can I fix it?
Move e.preventDefault() to else block when the validation condition fails. Also you don't need to resubmit the form using $("#frmContact").submit()
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult == vResult) { //""vResult"" is a value that I set when the page loads...
alert("good");
//$("#frmContact").submit();
}else{
e.preventDefault();
}
});
Or, you just modify statement as
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult !== vResult) { //""vResult"" is a value that I set when the page loads...
e.preventDefault();
}
alert("good");
});
Your form goes in infinite loop. try this simple code.
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult != vResult)
{
e.preventDefault();
}
});
Return true to allow the form to submit or false to suppress :
$('#frmContact').on('submit', function(e) {
if ($("#security").val() == vResult) {
alert("good");
return true;
} else {
return false;
}
});
Or, if the alert is not needed :
$('#frmContact').on('submit', function(e) {
return $("#security").val() == vResult;
});
You can let the jQuery event get prevented ...and trigger the native event
Just change
$("#frmContact").submit();
To
$("#frmContact")[0].submit();

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

AJAX POST incorrectly works like GET

I am trying to post contact page data to my view, but it stopped working when I included if else statements.
Here is my script:
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
}else
{
return true;
}
}
</script>
And here is my form:
<form class="contact-form">
{% csrf_token %}
<p class="input-block">
<label for="contact-name"><strong>Name</strong> (required)</label>
<input type="text" name="name" value="" id="contact-name" required>
</p>
<p class="input-block">
<label for="contact-email"><strong>Email</strong> (required)</label>
<input type="email" name="email" value="" id="contact-email" required>
</p>
<p class="input-block">
<label for="contact-subject"><strong>Subject</strong></label>
<input type="text" name="subject" value="" id="contact-subject">
</p>
<p class="textarea-block">
<label for="contact-message"><strong>Your Message</strong> (required)</label>
<textarea name="message" id="contact-message" cols="88" rows="6" required></textarea>
</p>
<div class="hidden">
<label for="contact-spam-check">Do not fill out this field:</label>
<input name="spam-check" type="text" value="" id="contact-spam-check" />
</div>
<input type="submit" value="Submit" onclick="javascript:Submit();">
<div class="clear"></div>
</form>
Without the if else it was working fine but now all pages are reloading with all form data as query parameters. How can I correct this?
First you need to prevent the default action if you are trying to do AJAX.
Since, I see you are already using jQuery. I recommend adding the following to the top of your <script>:
$("#contact-form").submit(function(e){
e.preventDefault();
Submit();
});
Obviously, you won't need this anymore..
onclick="javascript:Submit();"
Now run this code in any sort of javascript debugger (Chrome and Safari both have good ones) and you should be good!
Try this please..i hope it works...
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".contact-form").submit(function(e){
e.preventDefault();
Submit();
});
});
</script>
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
}
}
You need to return a false from your Submit() function. Also, call the function from the form tag using onsubmit handle.
<form class="contact-form" onsubmit="Submit();">
and in Submit() function:
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
} else {
return true;
}
Do not use javascript: in an onxxx event handler. javascript: is a protocol specifier that goes on a URL, but the onclick handler expects raw javascript, not a URL.
You need to return false from the onclick to prevent the default action of submitting the form. I assume you do want to prevent the default and use AJAX instead?

Categories

Resources