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.
Related
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>
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]);
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>
index.php
<form id="myForm" action="test2.php" method="POST">
<input type="submit" value="Print 1" name="submit" id="submit">
<input type="submit" value="Print 2" name="submit2" id="submit2">
</form>
<div id="ack"></div>
here's my script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/login_script.js"></script>
test2.php
<?php
if(isset($_POST['submit'])){
echo "1"; // i want to show this everytime i click submit (not working)
} // or what is the proper way to do this..
if(isset($_POST['submit2'])){
echo "2"; // i want to show this everytime i click submit2 (not working)
} // or what is the proper way to do this..
?>
login_script.js
$("#submit, #submit2").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("#ack").empty();
$("#ack").html(data);
});
$("#myForm").submit( function() {
return false;
});
});
if i remove the if(isset($_POST['submit'])).... its working...
so what is the proper way to do this..?
sorry im noob in ajax and jquery
No, you have to realize that <input type="submit" and <button> submit is not included in .serializeArray(), you'll have to just build the data object to be passed:
$("#submit, #submit2").click( function() {
var data = null;
if($(this).attr('id') == 'submit') {
values = {'submit': true};
} else {
values = {'submit2': true};
}
$.post( $("#myForm").attr("action"), values,
function(data) {
$("#ack").empty();
$("#ack").html(data);
});
});
Sample Demo
try with this:
$("#submit, #submit2").click( function() {
var formData = $(this).closest('form').serializeArray();
formData.push({ name: this.name, value: this.value });
$.post( $("#myForm").attr("action"),formData,
function(data) {
$("#ack").empty();
$("#ack").html(data);
});
$("#myForm").submit( function() {
return false;
});
});
Yes I just try it and below code is working for me please check.
index.php
<form id="myForm" action="test2.php" method="POST">
<input type="submit" value="Print 1" name="submit" id="submit">
<input type="submit" value="Print 2" name="submit2" id="submit2">
</form>
<div id="ack"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$("#submit, #submit2").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("#ack").empty();
$("#ack").html(data);
});
$("#myForm").submit( function() {
return false;
});
});
</script>
test.php
<?php
if(isset($_POST['submit'])){
echo "1"; // i want to show this everytime i click submit (not working)
} // or what is the proper way to do this..
if(isset($_POST['submit2'])){
echo "2"; // i want to show this everytime i click submit2 (not working)
} // or what is the proper way to do this..
?>
In the post it user name instead of the ID. Please try code below hope it will help you.
<form id="myForm" action="test2.php" method="POST">
<input type="submit" value="Print 1" name="submit" id="submit">
<input type="submit" value="Print 2" name="submit2" id="submit2">
</form>
I'm trying to submit a form, once the user has accepted they want to continue via the jQuery UI Dialog.
<form method="POST" action="url" onsubmit="return APP.dom.confirm(this);">
<button type="submit" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></button>
</form>
My APP.dom.confirm method looks like:
confirm: function(form) {
$("#dialog-confirm").dialog({
modal: true,
buttons: {
"Confirm": function() {
$(form).submit();
},
"Cancel": function() {
$(this).dialog("close" );
}
}
});
return false;
}
This works, however when they click confirm I'd like the form to get submitted.
$(form).submit();
That doesn't work. Logging it out I get the above HTML back. I've tried variations of, to no avail:
$(form).clostest('form').submit();
How do I submit this?
Change
$(form).submit();
to
form.submit();
When you call submit on a jQuery object, it calls your submit handler again. Calling it directly on the DOM element does not.
Example (interestingly, Stack Snippets won't let me submit a form, not even with target="_blank"):
var nesting = 0;
function submitHandler(form) {
var which = $(form).find("input[type=radio]:checked").val();
++nesting;
if (nesting > 5) {
snippet.log("Nested to 5, gave up");
} else {
if (which === "jQuery") {
snippet.log("Calling via jQuery, nesting = " + nesting);
$(form).submit();
} else {
snippet.log("Calling via DOM, nesting = " + nesting);
form.submit();
}
}
--nesting;
return false;
}
<form id="the-form"
onsubmit="return submitHandler(this);"
action="http://www.google.com/search"
target="_blank"
method="GET">
<input type="text" name="q" value="kittens">
<div>
<label>
<input type="radio" name="opts" value="jQuery"> Submit with jQuery
</label>
</div>
<div>
<label>
<input type="radio" name="opts" value="DOM"> Submit with DOM
</label>
</div>
<button>Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
confirm: function() {
var that = this;
$("#dialog-confirm").dialog({
modal: true,
buttons: {
"Confirm": function() {
$(that).submit();
},
"Cancel": function() {
$(this).dialog("close" );
}
}
});
}
Replace onsubmit="return APP.dom.confirm(this);" by
$('form').on('submit', APP.dom.confirm);