I have two forms of the same class in a page. These forms are exactly the same with the same elements. On submitting one of them, I try to access the elements inside. Here is what the forms look like:
<form role="form" class="login-form" id="login-form">
{% csrf_token %}
<div class="form-group">
<div class="input-icon">
<i class="icon fa fa-user"></i>
<input type="text" class="form-control" name="email" placeholder="Username" id="email">
</div>
</div>
<div class="form-group">
<div class="input-icon">
<i class="icon fa fa-unlock-alt"></i>
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
</div>
</div>
<div>
<!--input type="checkbox" id="remember" name="rememberme" value="forever" style="float: left;"-->
<label style="display: none; color: red;" id="incorrect_info">Veuillez vérifier vos informations</label>
</div>
<button class="btn btn-common log-btn">Se connecter</button>
</form>
Now the javascript where I try to access the elements:
$('.login-form').submit(function(e){
e.preventDefault();
// Get information
email = $(this).find('input[id="email"]').val();
pass = $(this).find('input[id="password"]').val();
$(this).find('label[id="incorrect_info"]').css('display','block');
});
This code works for the inputs, but not for the label, which is not found.
EDIT :
Sorry here is actually how the code looks like. The find is called in the ajax done.
$('.login-form').submit(function(e){
e.preventDefault();
// Get information
email = $(this).find('input[id="email"]').val();
pass = $(this).find('input[id="password"]').val();
$.ajax({
.......
}).done(function (data) {
if (data.success) {
window.location.href = data.url;
}
else {
$(this).find('label[id="incorrect_info"]').css('display','block');
}
});
});
I figured this out. The problem is that $(this) scope is different inside the ajax function. What I've done is to save it before getting into it, and reused it after:
$('.login-form').submit(function(e){
e.preventDefault();
// Get information
this_form = $(this);
email = $(this).find('input[id="email"]').val();
pass = $(this).find('input[id="password"]').val();
$.ajax({
......
success : function(data, status){
}
}).done(function (data) {
if (data.success) {
window.location.href = data.url;
}
else {
this_form.find('label[id="incorrect_info"]').css('display','block');
}
});
});
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've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;
When I click the submit button on my form my registration page refreshes without the form data being posted to my database.
My HTML markup looks like this -
<form id="reg">
<div class="form-group">
<label style="color: white; text-align:center" for="username">Username</label>
<input style="color: #C0C0C0;" type="text" name = "username" class="form-control" id="username" placeholder="Enter Username">
</div>
<div class="form-group">
<label style="color: white; text-align:center" for="password">Password</label>
<input style="color: #C0C0C0;" type="password" name = "password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label style="color: white; text-align:center" for="email">Email</label>
<input style="color: #C0C0C0;" type="text" name = "email" class="form-control" id="email" placeholder="Enter Email">
</div>
<button type="submit" name = "submit" class="btn btn-primary">Submit</button>
And my jquery code -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#reg').on('submit', function(e) {
e.preventDefault
$.ajax({
url:'script/register.php',
data: $(this).serialize(),
type:'POST',
success:function(results) {
$(".result").html(results);
}
});
});
</script>
I am not sure where I am going wrong. The page refreshes and I see the forms variables and values in the url bar. Any help with the above is greatly appreciated. Thanks
Check your syntax: preventDefault is a function.
$('#reg').on('submit', function(e) {
e.preventDefault() <---- Here fails
$.ajax({
url:'script/register.php',
data: $(this).serialize(),
type:'POST',
success:function(results) {
$(".result").html(results);
}
});
});
Replace your ajax code with the following
<script>
$('#reg').on('submit', function(e) {
$.ajax({
url:'script/register.php',
data: $(this).serialize(),
type:'POST',
success:function(results) {
$(".result").html(results);
}
});
return false;
});
</script>
You should return false to prevent page refresh.
I have problem with AJAX and jQuery. I write function for login to system, but it works only first time. Here is my code:
html in modal:
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
here is jquery:
function login(){
login=document.getElementById('userName').value;
pass=document.getElementById('password').value;
var dataString="emailLogin="+login+"&passLogin="+pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text){
if(text=='0'){
$("#loginError").removeClass('hidden');
}else{
$("#loginOk").removeClass('hidden');
$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">"+login+" (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html(""+login+" (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
}
});
return false;
}
You are overwriting your login function with a string.
function foo() {
alert('foo');
foo = function () {
alert('bar');
}
}
<a onclick="foo()">
click me!
</a>
See how the second click here causes a different alert? In your case you're replacing the function with a string instead of a function, causing a syntax error. Don't forget to var your variables.
var login=document.getElementById('userName').value;
var pass=document.getElementById('password').value;
The snippet tests your logic and there was a console error for your login and pass variables. I set them as 'var' and put your success logic in the 'error' section of the ajax request since I cannot reach your server, but it does create the logout button. Is that what you wanted?
function login() {
var login = document.getElementById('userName').value;
var pass = document.getElementById('password').value;
var dataString = "emailLogin=" + login + "&passLogin=" + pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text) {
/* Success logic */
},
error: function() {
alert('Test - success logic');
$("#loginOk").removeClass('hidden');
//$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">" + login + " (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html("" + login + " (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
<div id="loginLi"></div>
<div id="regLi"></div>
<div id="loginOk">Login OK</div>
I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});