jquery submit form and stay on same page not working - javascript

The code below is supposed to submit the form and stay on the current page. It does submit the form, but it doesn't stay on the same page as it redirects to the form processing page. I have tried using event.preventDefault(); and return false; but neither are stopping the redirect. I tried them one at a time and then later added both at the same time and at different locations in the function, but the redirect still happens.
function submitForm() {
var $subForm = $('#signupForm')[0] ;
if (!$subForm.checkValidity()) {
$subForm.find(':submit').click() ;
return ;
}
$subForm.submit(function(event){
event.preventDefault(); // not working here
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
return false ; // not working here
}
My form is defined as:
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
....
<button type="button" onclick='submitForm();' id="ccInfoButton" style="" class="btn btn-primary buttonSignup" disabled >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>

The issue is because of where you are trying to handle the submit event. The code below achieves the goal of submitting the form and staying on the same page. You can see it work with the code snippet below.
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // not working here
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
<input type="text" name="eee" required/>
<input type="submit" style="display: none;" required/>
<button type="button" onclick='submitForm();' id="ccInfoButton" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
<!DOCTYPE html>
<html>
<body>
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
<input type="text" name="eee" required/>
<input type="submit" style="display: none;" required/>
<button type="button" onclick='submitForm();' id="ccInfoButton" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // now working
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
</script>
</html>

#DankyiAnnoKwaku - kudos to Dankyi for getting me on the right track, but his solution didn't work for me, I had to adapt it a bit more:
<script type="text/javascript">
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
// Had to wrap the `submit(function(event)` in the root `$(document).ready ....`
$(document).ready(function(event) {
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // now working
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
}) ;
</script>

Related

Html form submit after ajax

Trying to make some database validation with Jquery Get method before submitting a form. But I get the error
Uncaught TypeError: form.submit is not a function
Got the logic form here
Simplified Code below (but the err is still there...)
<html>
<body>
<div id="insertCertificateForm">
<form action="/Certificates/Insert" method="post">
<div>
<label>Charge</label>
<input name="Charge" id="Charge" />
</div>
<input type="submit" value="Insert" class="btn btn-default" />
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#insertCertificateForm').submit(function (e) {
e.preventDefault();
var form = this;
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
form.submit();
}
else {
return false;
}
});
});</script>
</body>
</html>
Because after clicking button this would mean the current button and
insertCertificateForm was never a form anyways...it was Div
best would be to bind the form with an ID #myForm
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="insertCertificateForm">
<form id="Myform" action="/Certificates/Insert" method="post">
<div>
<label>Charge</label>
<input name="Charge" id="Charge" />
</div>
<input type="submit" value="Insert" class="btn btn-default" />
</form>
</div>
<script>
$('#insertCertificateForm').submit(function (e) {
e.preventDefault();
var form = $("#Myform");
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
form.submit();
} else {
return false;
}
});
});
</script>
</body>
</html>
and also load your scripts in the head
Your selector is wrong $('#insertCertificateForm'), if you want to do like this you need to add this id into your form <form id="insertCertificateForm" otherwise follow this way,
$('form').submit(function (e) {
e.preventDefault();
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
$(this).submit();
} else {
return false;
}
});
});
That's because you're calling this and not $(this) when declaring the form variable. You can either declare it as $(this) or use $(form) to submit the form.

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

Preview data form

I need some help, I have a form that before the 'Send' button have a select type 'check' if this is uncheck and the people click on 'send' the form show a pop up with the preview of the all data in the form, if the select is check and the people click on 'send' this is sending normal, but I would like change that, I would like change the select check to a button 'Preview' and when the people click show the pop up with the preview, and the send buttom continue normal send the form.
this is the code for the pop up with the rule if is check or uncheck.
function check_form() {
var url = "process_estaform.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#estafrm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#dialog").html(data);
if($("#senditornot").prop("checked") === false ) {
$("#dialog").attr("title","This dialog box will automatically close.");
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
},
error :function() {
$("#dialog").html(data);
$("#dialog").attr("title","This dialog box will automatically close.");
if($("#senditornot").prop("checked") === false ) {
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
}
});
}
code html.
<div class="container">
<input type="checkbox" name="sendit" id="senditornot" />
</div>
<br>
<div class="container">
<div align="center">
<input type="submit" id="submitter" value="Submit" />
</div>
</div>
img form
Add following before function check_form.
$("#preview").click(function()
{
var previewData = $("#estafrm").serialize();
$("#dialog").html(previewData);
})
add preview button in code.html
<input type="button" name="preview" id="preview" value="preview" />
Added complete code.
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function check_form() {
var url = "process_estaform.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#estafrm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#dialog").html(data);
if($("#senditornot").prop("checked") === false ) {
$("#dialog").attr("title","This dialog box will automatically close.");
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
},
error :function() {
$("#dialog").html(data);
$("#dialog").attr("title","This dialog box will automatically close.");
if($("#senditornot").prop("checked") === false ) {
$("#dialog").dialog();
$("#dialog").delay(5000).fadeOut("slow",function(){ $('#dialog').dialog('close'); }).css('display','block');
}
else {
$("#dialog").delay(5000).fadeOut("slow").css('display','block');
}
}
});
}
$("#preview").click(function(){
var previewData = $("#estafrm").serialize();
console.log(previewData);
$("#dialog").html(previewData);
alert(previewData);
})
})
</script>
<body>
<form name="estafrm" id="estafrm">
<div class="container">
<input type="text" name="name" id="name" value=""/>
<input type="checkbox" name="sendit" id="senditornot" />
</div>
<br>
<div class="container">
<div align="center">
<input type="submit" id="submitter" value="Submit" />
<input type="button" name="preview" id="preview" value="preview" />
</div>
</div>
</form>

Ajax to submit a button click to php, then to a serial device

I am trying to get button to to initiate a function on a serial device, an arduino, by means of ajax and php, but cannot seem to figure it out.
Here is my html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(function() {
$('#contact_form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: $('#contact_form').serialize(),
success: function() {
alert('form was submitted');
}
});
return false;
});
});
</script>
<meta charset="utf-8">
<title>Enroll</title>
</head>
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<input type="submit" name="rcmd" class="button" id="submit_btn" value="Enroll" /><br />
</fieldset>
</form>
</div>
And here is my php:
<?php
$verz="1.0";
$comPort = "/dev/ttyACM0"; /*change to correct com port */
$PHP_SELF="index.php"; //This php file locate it from root
if (isset($_POST["rcmd"])) {
$rcmd = $_POST["rcmd"];
switch ($rcmd) {
case Stop:
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 1); /* this is the number that it will write */
fclose($fp);
break;
case Enroll:
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 3); /* this is the number that it will write */
fclose($fp);
break;
default:
die('Crap, something went wrong. The page just puked.');
}/*end switch case*/
}/*end if statement*/
?>
When I run it, I get the dialog box that says the form was submitted, but the serial device does not respond to it. Any help would be greatly appreciated.
I change listenner to detect click on button and i get the value with $(this).val()
Javascript :
<script type="text/javascript">
$(function() {
$('#contact_form').on('click', '.button',function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: 'rcmd='+$(this).val(),
success: function() {
alert('form was submitted');
}
});
return false;
});
});
</script>
Html :
<input type="button" class="button" id="submit_btn" value="Enroll" />

Submit form via Enter key and Submit button both

Hi I have form and following things are bothering me:
1. Form does not submit on pressing enter.
2. When i press enter in input field then Search Now button needs to be pressed
twice to search places.
Form is displayed as below:
<form method="POST" id="mylocform" action="">
<h3 class="animated slideInLeft delay-2">
<input type="text" placeholder="Start Typing Your Location" id="geocomplete"
style="color:black;width:100%;padding:5px;height:45px;border-radius:5px"
autocomplete="off" class="chkmeloc" onblur="checkmylocform()"/></h3>
<input type="submit" class="btn btn-default btn-lg animated fadeInUpBig delay-3"
style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>
</form>
Validation goes like below:
$(document).ready(function(){
$("form#mylocform").submit(function(event) {
event.preventDefault();
validate();
});
});
function checkmylocform(){
var checkOdlen = $(".chkmeloc").val().length;
if(checkOdlen==0){
$(".chkmeloc").css("border-color","#F05F68");
$(".chkmeloc").focus();
$(".chkmelocmess").html('<button type="submit" class="btn btn-default
btn-lg" style="background: #FFF;color:red">
<i class="fa fa-warning text-red"></i>
Select Your Location</button>');
return false;
}
else{
$(".chkmeloc").css("border-color","#0C9");
$(".chkmelocmess").html('<input type="submit" class="btn btn-default
btn-lg" style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>');
return true;
}
}
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkmylocform()){
return false;
}
else{
submitform();
}
}
Submit Form has code to submit form via ajax as below. Please help me to get out of this situation.
$("Your selector").keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$(input[type = submit]).click();
return false;
}
});
look at this site:
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
the site says that enter key is automaticly a submit in al browser
Try This
File index.html :
<form class="form-inline" action="" method="POST">
<input type="password" name="token" placeholder="Enter Facebook access token..." class="subscribe-email">
<button type="submit" class="btn">Start!</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
File script.js :
$('.get_token form').submit(function(e) {
e.preventDefault();
var postdata = $('.get_token form').serialize();
$.ajax({
type: 'POST',
url: 'assets/submit_token.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.get_token form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});

Categories

Resources