I have a situation where i have the same form multiple times on a page in my application which allows users to edit or remove data however when using the below javascript to listen for the form submission the page just refreshes.
I was going to use $('.service_form').serialize() to submit the forms however when doing so it serializes values from every form on the page and completes the ajax request however if i use $(this).serialize() the page just refreshes.
HTML Form
<div id="service_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form class="service_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class='form-group has-feedback has-feedback-left'>
<label for="service_idno">IDNO:</label>
<input type="text" class="form-control required" id="service_idno" name="service_idno">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_code">Service Code:</label>
<input type="text" class="form-control required" id="service_code" name="service_code">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_cost">Service Cost:</label>
<input type="number" class="form-control required" id="service_cost" name="service_cost">
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Commit" class="btn btn-success" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
Javascript
$('.service_form').each(function(){
$(this).validate({
errorClass: 'validation-error-label',
highlight: function(element, errorClass) {$(element).removeClass(errorClass);},
errorPlacement: function(error, element){if (element.parents('div').hasClass('has-feedback')) {error.appendTo(element.parent() );}},
rules:{vali: "required"},
messages: {
service_idno: {required: "* Service IDNO Is Required."},
service_code: {required: "* Service Code Is Required."},
service_name: {required: "* Service Name Is Required."},
service_account: {required: "* Account Is Required."},
service_cost: {required: "* Cost Is Required."},
service_retail: {required: "* Retail Is Required."},
},
submitHandler: function(form) {
$.ajax({
url: "rest/servicedelete.php",
type: "POST",
data: $(this).serialize(),
timeout:9000,
beforeSend:function() {
$('.modal').modal('hide');
},
success: function (data) {
},
error:function() {
$('#notification').html('Remote Service Currently Unavailable');
},
});
}
});
});
I am wanting to be able to submit any form on the page at any time and only submit that data.
The scope of submitHandler() is not the form element, hence this is not what you expect it to be. Use the provided form parameter instead:
data: $(form).serialize(),
first you need to store current form in a temp variable like
$('.service_form').each(function(){
var form = $(this);
and then you do the serialize like
data: $(form).serialize(),
that will fix your issue.
Related
I'm unable to keep my AJAX call inside the same page. It keeps posting my form without any of the tried preventDefault() tries.
Here's my full code for a form ID "#leadform" and a button ID "#submitButton".
$(document).ready(function() {
$("#submitButton").on('click', function(e) {
e.preventDefault();
$('#leadform').submit();
});
$("#leadform").validate({
rules: {
Mobile: {
required: true
},
email: {
required: true
}
},
messages: {
Mobile: {
required: "Please enter a valid phone number"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$("#response").addClass("alert alert-info").text("Do not close this window, it may take a minute to complete!");
var formData = $('#leadform').serialize();
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
dataType: 'text', // json
beforeSend: function(data) {
//console.log(data);
},
success: function(data) {
$("#response").removeClass("alert-info").delay(200).addClass("alert-success").text("Thank you for your request! You can now close this window");
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
}
});
return false;
}
});
});
I have tried a lot of options, read about all the SO posts and none helped.
Alternatives I tried are:
Without $('#leadform').submit(); called seperately, but from within the same function.
e.preventDefault from within the submithandler (added e to the function of course).
Tried with and without that return false line.
Whatever I tried (tried for hours literally), it goes straight to the php file. When I remove the validate function and include the ajax normally via the submit button click function, it works fine and as expected (it just won't validate my last step in the form wizzard so i need to make a validation for that last step.
I hope anybody can help me out.
Thanks.
Added HTML Section (shortened)
<form action="submit.php" name="leadform" id="leadform" method="POST" accept-charset="utf-8" class="js-wizard-validation2-form">
<div id="_Mobile" class="form-group">
<label class="control-label" for="Mobile">Mobile Number</label>
<input type="text" name="Mobile" id="Mobile" minlength="10" maxlength="16" placeholder="Phone number here" class="form-control required input_text" required="">
</div>
<div id="_Email" class="form-group">
<label class="control-label" for="Email">Email Address</label>
<input type="email" name="Email" id="Email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" placeholder="Email here" autocorrect="off" autocapitalize="off" class="form-control input_text" required="">
</div>
<div class="block-content block-content-sm block-content-full bg-body-light rounded-bottom" style="margin-top:20px;">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-lg btn-alt-secondary" data-wizard="prev">
<i class="fa fa-angle-left mr-1"></i> Previous
</button>
</div>
<div class="col-6 text-right">
<button type="button" class="btn btn-lg btn-info" data-wizard="next">
Next<i class="fa fa-angle-right ml-1"></i>
</button>
<button type="submit" id="submitButton" class="btn btn-lg btn-success d-none" data-wizard="finish">
<i class="fa fa-check mr-1"></i> Submit </button>
</div>
</div>
</div>
</form>
According to the docs, you can actually trigger the validator without submitting the form.
var validator = $( "#leadform" ).validate();//your entire validation script goes here, its left out for brevity
$("#submitButton").on('click', function(e) {
e.preventDefault();
validator.form();
});
I got a strange problem when creating a login form for a website I create for work. I know it has been posed a million times but my case only breaks in Edge.
Principle is: I have a form with username and password. When submitting the form user and pass is validated and logged in in ajax (and returns error if so). If valid it redirects to the main user. (simple, no?)
Problem is that the page is refreshed anyway even if the form have return: false, but only in Microsoft Edge. It works on Chrome, IE (even in document mode 10) and Firefox with no problems.
Code in action:
<!-- jQuery + validate plugins are already loaded -->
<form id="loginform" method="post" class="">
<div class="navbar-login panel">
<div class="panel-heading">
<h4 class="panel-title">Connexion au cours</h4>
</div>
<div class="panel-body">
<div id="login-warning"></div>
<div class="form-group col-md-12">
<input class="form-control" style="width: 100%;" placeholder="Adresse email" name="LOGIN_EMAIL" type="email">
</div>
<div class="form-group col-md-12">
<input class="form-control" style="width: 100%;" placeholder="Mot de passe" name="LOGIN_PASSWORD" type="password">
</div>
</div>
<div class="panel-heading text-right" style="display: table;width: 100%;">
<button type="submit" style="float: right;display: inline-block;" class="btn btn-info">Connexion</button>
</div>
</div>
</form>
JS:
$("#loginform").validate({
debug: false,
rules: {
LOGIN_EMAIL: {
required: true,
email: true
},
LOGIN_PASSWORD: {
minlength: 6
}
}
});
$("#loginform").submit(function(e){
var f = $(this);
if(f.valid()){
$.ajax({
url: "req/ajx_login.php",
type:"POST",
cache: false,
async: false,
data: f.serialize(),
success: function(data, status, xhr){
// data is "success" if successed, anything else if failed
if(data == "success"){
location = "/cours";
}else{
$("#login-warning").html(data);
}
}
});
}
return false;
});
Can someone help? Thanks for future answers.
Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;
I'm pretty new in web development and I know this might sound like a very simple question but I'm trying to add a login functionality in a bootstrap template.
The .js with the template validates the contents of the text and such. I'm trying to add a POST function in the submitHandler.
$(document).ready(function() {
$('#login-form').validate({
focusInvalid: false,
ignore: "",
rules: {
txtusername: {
minlength: 2,
required: true
},
txtpassword: {
required: true,
}
},
invalidHandler: function (event, validator) {
//display error alert on form submit
},
errorPlacement: function (label, element) { // render error placement for each input type
$('<span class="error"></span>').insertAfter(element).append(label)
var parent = $(element).parent('.input-with-icon');
parent.removeClass('success-control').addClass('error-control');
},
highlight: function (element) { // hightlight error inputs
},
unhighlight: function (element) { // revert the change done by hightlight
},
success: function (label, element) {
var parent = $(element).parent('.input-with-icon');
parent.removeClass('error-control').addClass('success-control');
},
submitHandler: function(form) {
var username=$("#txtusername").val();
var password=$("#txtpassword").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
success: function(data){
if(data) {
window.location.href = "index.php";
} else {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
});
});
<?php
if (isset($_POST['submit'])) { // Form has been submitted.
$username = ($_POST['username']));
$password = ($_POST['password']));
.
.
.
.
.
}
else
{
echo "Doesnt Work";
}
?>
.
.
.
<form id="login-form" class="login-form" action="#" method="post">
<div class="row">
<div class="form-group col-md-10">
<div id="error"></div>
<label class="form-label">Username</label>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="text" name="txtusername" id="txtusername" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-10">
<label class="form-label">Password</label>
<span class="help"></span>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="password" name="txtpassword" id="txtpassword" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<button class="btn btn-primary btn-cons pull-right" type="submit">Login</button>
</div>
</div>
</form>
Thanks in advance!
Please check the documention of data sent to the server. You can use object to send your data. In the link above, there are some examples how to send data to server.
var dataString = {username: username, password: password}
I'm using the jQuery Validation Plugin, and I have a problem.
Both my jQuery and HTML is perfectly valid (according to JSLint and the WC3 Markup Validation Service), but when I hit the submit button, nothing happens.
My code even clearly states that, upon submitting, an alert should pop up, but even that doesn't work. The form is however validated correctly, and in the and, all fields are green (meaning they passed validation) but it doesn't actually submit (nothing happens).
Also, in my DevTools, the console does not report any errors.
Possibly/probably relevant; the email-textfield and the username-textfield are both being checked by a remote PHP script. This script works, strange enough, only after the second time. So when I first leave (blur) the email-textfield, nothing happens, it's isn't marked correct nor false.
Only when I (re-enter and) leave the textfield for the second time, it is validated, or when I hit the submit button. (This shows the submit button is actually connected, it just simply does not submit)
I really hope someone will solve my problem. I'm not trying to just let someone else do the work. I validated, checked, debugged, but nothing solved my problem.
My HTML (it's in a modal using Bootstrap):
<div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="signupform" method="post" action="/" role="form">
<div class="modal-body" style="padding-bottom: 5px;">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p class="lead">For creating an account,</p>
<p class="lead text-right">you'll have to give us some information.</p>
<div id="emailgroup" class="form-group">
<label for="signupemail"> Your Emailaddress</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-envelope"></span> </span>
<input type="email" name="signupemail" spellcheck="false" autocomplete="on" required class="form-control" id="signupemail" placeholder="Email">
</div>
<label class="control-label error-label" for="signupemail"></label>
</div>
</div>
<div id="fnamegroup" class="form-group">
<label for="inputfname"> Your Full Name</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-user"></span> </span>
<input type="text" name="fname" required class="form-control" id="inputfname" placeholder="Barack Obama">
</div>
<label class="control-label error-label" for="inputfname"></label>
</div>
</div>
<div id="unamegroup" class="form-group">
<label for="inputuname"> Your Username</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> # </span>
<input type="text" name="uname" required class="form-control" id="inputuname" placeholder="PresidentofAmerica">
</div>
<label class="control-label error-label" for="inputuname"></label>
</div>
</div>
<div id="thepasswordgroup" class="form-group">
<label for="thepassword"> Your Password</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-lock"></span> </span>
<input type="password" name="thepassword" required class="form-control" id="thepassword" placeholder="123456789" autocomplete="off">
</div>
<label class="control-label error-label" for="thepassword"></label>
</div>
</div><br />
<div id="gendergroup">
<label>Your Gender</label>
<div class="radio">
<label class="checkbox-inline"><input type="radio" name="gendergroup" id="gendergroupmale" value="male" checked>I'm a Male</label>
</div>
<div class="radio">
<label class="checkbox-inline"><input type="radio" name="gendergroup" id="gendergroupfemale" value="female">I'm a Female</label>
</div>
</div>
<br />
<div class="form-group">
<label for="taccheckbox"> Terms and Conditions</label>
<div class="col-lg-10">
<div class="input-group"><span class="input-group-addon">
<input id="taccheckbox" name="taccheckbox" type="checkbox" required>
</span>
<input style="cursor:default !important;" type="text" id="something" value="I accept the Terms and Conditions" readonly class="form-control">
</div>
<label class="control-label error-label" for="taccheckbox"></label>
<!-- /input-group -->
</div>
<!-- /.col-lg-6 -->
</div>
</div>
<div class="modal-footer">
<p>
Have already got an account? <strong>Login here!</strong></p>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="signupsubmitbtn" class="btn btn-primary" value="Sign Up">
</div>
</form>
</div>
</div>
</div>
My Javascript/jQuery:
$('#signupform').validate({
rules: {
signupemail: {
required: true,
email: true,
remote: {
url: "/functions/verifysignup.php",
type: "post"
}
},
fname: {
required: true,
minlength: 8,
maxlength: 30
},
uname: {
required: true,
minlength: 6,
maxlength: 20,
remote: {
url: "/functions/verifysignup.php",
type: "post"
}
},
thepassword: {
required: true,
minlength: 5,
maxlength: 20
},
taccheckbox: "required"
},
messages: {
email: {
remote: "This emailaddress is already in use"
},
taccheckbox: {
required: "You have to accept the Terms and Conditions"
},
fname: {
minlength: "At least 8 characters required",
maxlength: "Max. 30 characters"
},
uname: {
minlength: "At least 6 characters required",
maxlength: "Max. 20 characters",
remote: "This username is already in use"
}
},
submitHandler: function (form) {
alert('called');
$('#signupsubmitbtn').prop("disabled", false);
//^[a-zA-Z0-9_-]{6,15}$ username
form.submit();
},
errorPlacement: function (error, element) {
if (element.attr('id') == "taccheckbox") {
error.appendTo(element.parent().parent().next());
} else {
error.appendTo(element.parent().next());
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$('#signupsubmitbtn').prop("disabled", true);
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error').find('label.control-label label').text('');
if ($('.has-error').length === 0) {
$('#signupsubmitbtn').prop("disabled", false);
}
},
success: function (element) {
element.closest('.form-group').removeClass('has-error').addClass('has-success');
if ($('.has-error').length === 0) {
$('#signupsubmitbtn').prop("disabled", false);
}
//element.parent().next().text('');
}
});
My remote PHP script:
<?php
define ('INCLUDE_CHECK',true);
require('connect.php');
if(isset($_REQUEST['signupemail'])){
$email = mysqli_real_escape_string($link, $_REQUEST['signupemail']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE email=\"".$email."\""));
if($thearray[0] > 0){
echo '"This emailaddress is already in use"';
} else {
echo "True";
}
} else if(isset($_REQUEST['uname'])){
$uname = mysqli_real_escape_string($link, $_REQUEST['uname']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE uname=\"".$uname."\""));
$forbiddennames = array(1 => 'super-user','superuser', 'root', 'admin', 'administrator', 'system', 'website', 'site', 'owner', 'manager', 'founder','moderator');
if(in_array(strtolower($_REQUEST['uname']), $forbiddennames)) {
echo '"'.$_REQUEST['uname'].' is a forbidden username"';
} else if($thearray[0] > 0){
echo '"This username is already in use, please choose another"';
} else {
echo "True";
}
}
?>
Everything looks very close to correct to me. One issue is that you have your php script echoing True back, but it has to be true (lower case). That actually matters.
Otherwise, IMO your script looks fine.
The stuff you're saying about it not calling your submitHandler, or only triggering the remote bits doesn't really seem to be the case to me. I copied your code and simply added a bit of debugging (i.e. to console.log when remote gets triggered or when submitHandler gets called) and both got called at the appropriate times.
For instance, if you type a valid email and then click to the next field, it immediately validates the email address.
So whatever issues you're having, are not related to the code you've shown (except for that one error with true vs True).
Here's a working example of your code, for reference: http://jsfiddle.net/ryleyb/tWH9M/1/
In order to test it with remote working teh way you have it setup, you have to find this bit:
signupemail: {
required: true,
email: true,
remote: {
url: '/echo/json/',
data: {
json: function () {
return 'true';
}
},
complete: function (data) {
$('#log').append('remote signupemail triggered<br>');
},
type: 'post'
},
},
And change that return 'true'; to return 'True';