I have a little form in my modal which looks like this:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="edited_email" class="form-control" id="edit_email" value="">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
and I want to prevent the form to submit if the user enters an email that it is already in my database. I have the following script:
$("#check_email").click(function() {
var email = $(this).parent().siblings().find("#email").val();
var that = $(this);
$(this).parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
});
});
The problem is that if I put the even.preventDefault() in that else condition, the $.get() seems to not trigger, because I guess that the form submits faster. Otherwise if I put the event.preventDefault() right after the .submit(function( event ) { then I can't unbind the submit to work after the user changes the email.
What I am doing wrong?
P.S.
My php file looks like this:
<?php
include "connect.php";
if(isset($_GET['email']) && !empty($_GET['email'])){
$sql = "SELECT * FROM users WHERE email='".$_GET['email']."';";
$result = $conn->query($sql);
if ($result->num_rows > 0){
echo "The email is already in our database. Please try another one!";
}
}
?>
I understand you would like to avoid form sending if email is already used.
At first, where is your magic button to do this :D ?
I added button in example.
You must be sure that your "this" is element you want, creating structure like .parent().parent().parent() everywhere is stupid - one change and everything not work.
Next thing to avoid form submit you must return false; inside submit function, preventDefault() work with <a> or other events like click
And next.. if you send ajax your callback function can back to your browser after your submit click.
For example checkClick -> sendAjax -> submitClick -> ajaxBack
And next :D - PHP: Your form have method="post" but server use $_GET
So.. if you send post you must use $_POST if get than $_GET
This time you used $.get so i dont know your ajax configuration but this can cause errors.
Here is some code but im sure this is not final implementation you want, but it should help :)
sorry for english btw.
html:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="edited_email" class="form-control" id="edit_email" value=""> <button type="button" id="check_email" data-dismiss="modal">check</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
javascript:
$("#check_email").click(function() {
var email = $(this).parent().find("#email").val();
var that = $(this);
alert(email);
console.log($(this).parent().parent().parent())
$(this).parent().parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
return false;
});
});
Related
Trying to verify form input via a jQuery get request, but function does not get called.
Tried using just the jQuery (without function), the $.get works and returns proper values. I need the function approach to return false if (and stop form from submitting) if condition is not met.
<form onSubmit="return checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName() {
$(document).ready(function () {
$("button").click(function () {
$.get("/check?username=" + document.getElementById('1').value, function (data, status) {
alert(data);
return false;
});
});
});
}
</script>
I expect the function to be called, return true if input verified (and go on with form submission) and false (stop form from submitting) if verification fails.
It isn't common practice to put events within the html anymore, as there is addEventListener. You can add it directly from the javascript:
document.querySelector('form').addEventListener('submit', checkName)
This allows for easier code to navigate, and makes it easier to read.
We can then prevent the form form doing it's default action by passing the first parameter to the function, and calling .preventDefault() as you can see from the modified function below. We no longer need to have return false because of it.
document.querySelector('form').addEventListener('submit', checkName)
function checkName(e) {
e.preventDefault()
$.get("/check?username=" + document.getElementById('1').value, function(data, status) {
alert(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
You're returning false from the async handler function. As such, that's not going to stop the form from being sent.
A better solution would be to always prevent the form from being submit then, based on the result of your AJAX request, submit it manually.
Also note that it's much better practice to assign unobtrusive event handlers. As you're using jQuery this is a trivial task. This also gets you access to the Event object which was raised by the form submission in order to cancel it. Try this:
<form action="/register" method="post" id="yourForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
$(document).ready(function() {
$("#yourForm").on('submit', function(e) {
e.preventDefault();
var _form = this;
$.get('/check', { username: $('#1').val() }, function(data, status) {
// interrogate result here and allow the form submission or show an error as required:
if (data.isValid) { // just an example property, change as needed
_form.submit();
} else {
alert("Invalid username");
}
});
});
});
You need to return from function not from inside the callback, and you do one if you assign to onsubmit you don't need click handler. And also click handler will not work if you have action on a form.
You need this:
function checkName() {
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
});
return false;
}
this is base code, if you want to submit the form if data is false, no user in db then you need something like this (there is probably better way of doing this:
var valid = false;
function checkName() {
if (valid) { // if valid is true it mean that we submited second time
return;
}
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
if (data) { // we check value (it need to be json/boolean, if it's
// string it will be true, even string "false")
valid = true;
$('form').submit(); // resubmit the form
}
});
return valid;
}
You can mark all your fields as required if they cannot be left blank.
For your function you may use the below format which works for me.
function checkName() {
var name = $("#1").val();
if ('check condition for name which should return true') {} else {
return false;
}
return true;
}
Just write the name of the function followed by (). no need to write return on onsubmit function call
function checkName()
{
$(document).ready(function(){
$("button").click(function(){
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
return false;
});
});
});
}
<form onSubmit="checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
I think if you replace button type from submit to button and then on button click event, inside get request, if your condition gets true, submit the form explicitly, would help you too achieve what you require.
You should remove the document.ready and the button event click.
EDITED
Adding an event parameter to checkName :
<form onSubmit="return checkName(event);" action="/register" method="post" id="myForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName(e){
e.preventDefault();
e.returnValue = false;
$.get("/check?username=" + document.getElementById('1').value,
function(data, status){
if(data) // here you check if the data is ok
document.getElementById('myForm').submit();
else
return false;
});}
</script>
I did a form validation where server checks submitted data. If data passes validation, then redirect to previous page, if not, a modal box will pop up tells user wrong username/password.
The question is, after user resubmit the form, redierct function doesn't work. It only works when user first time successfully input those fields. Can anyone help me with this please?
The html code:
<div id="formInfo">
<form method="post" action="<?PHP echo $_SERVER['PHP_SELF'];?>">
<span class="title">Sign in to urmajesty.net</span><br><br>
<div id="input_container">
<input type="text" name="username" placeholder="username"><img src="Images/icons/user.png" id="input_img"><br><br>
</div>
<div id="psw_container">
<input type="password" name="psw" placeholder="password"><img src="Images/icons/key.png" id="key_img"><br><br>
</div>
<div id="checkbox">
<input type="checkbox" name="RememberUsername" value="Yes"><span class="checkboxtxt">Remember my username</span>
</div><br><br>
<div id="Forget">
<span class="forget1">Forget Password</span><span class="forget2">Forget Username</span>
</div>
<input type="submit" class="button" value="SIGN IN"><br><br>
<div id="hispan"><p class="hip"><span class="hi">New to urmajesty.net?</span></p></div><br>
<input class='disable_me' name="referer" type="hidden" value="<?php echo urlencode($_SERVER['HTTP_REFERER'])?> " />
<button type="button" class="button" id="btn">CREATE ACCOUNT</button>
</form>
</div>
<div id='modal_box'>
<div class='modal_content'>
<span class='close'>×</span><p>username/password is wrong. Please try again!</p>
</div>
</div>
The php code:
if($_SERVER["REQUEST_METHOD"]=="POST"){
$validation=Login();
if($validation==false){
echo"<script>
var modal_box=document.getElementById('modal_box');
modal_box.style.display='block';
modal_box.style.backgroundColor='rgba(0,0,0,0.4)';
var close=document.getElementsByClassName('close')[0];
close.onclick=function(){
modal_box.style.display='none';
}
window.onclick=function(event){
if(event.target==modal_box){
modal_box.style.display='none';
}
}
</script>";
}
else{
if(!empty($_POST['referer']) && !is_array($_POST['referer'])){
header("Location: ".urldecode($_POST['referer']));
exit();
}
}
}
?>
Use javascript to redirect.
if(!empty($_POST['referer']) && !is_array($_POST['referer'])){ ?>
//header("Location: ".urldecode($_POST['referer']));
<script>
window.location.href = "<?=$_POST['referer']?>";
</script>
<?php
exit();
} ?>
Apart from using header() to redirect, you can use meta refresh method, or JS window.location method.
<script>
window.location = "<?=$_POST['referer']?>"
</script>
I am having a little problem here for some reason. I have another page with almost the exact same code and it redirects the user to the page that I want them to go to. For some reason this one does not. I have tried commenting out the if statement and everything down to the point of just having the window.location.replace with the click action and still no luck.
JS
$(document).ready(() => {
$("#login-button").click(() =>{
if($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.replace('../index.html');
} else {
alert("You have the wrong password and username");
}
});
});
HTML
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
You're mistaking what location.replace() is used for. To redirect, use location.href instead.
window.location.href = '../index.html';
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
You also need to prevent the form submit. This is causing the page to be posted back to itself. Add the following inside your form submit event handler.
e.preventDefault();
You just need to stop the default form submit
html
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
jQuery
$(function() {
$("#login-button").click((e) {
if ($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.href('../index.html');
e.preventDefault();
} else {
alert("You have the wrong password and username");
e.preventDefault();
}
});
});
I want to perform validation before any other onsubmit actions. Unfortunately, I have no control over the value of the onsubmit attribute on the form. So for example:
<form id="myForm" onsubmit="return stuffICantChange()"></form>
I've tried the following code, and several other methods, with no luck:
$("#myForm").onsubmit = function() {
console.log("hi");
}
Any help is appreciated, thanks.
If this is a duplicate, please let me know before marking it as such so that I can refute the claim if necessary.
EDIT:
My code as requested:
<form id="form_ContactUs1" name="form" method="post" action="index.php" onsubmit="return Validator1(this) && ajaxFormSubmit(this); return false">
<div class="form">
<div class="form-staticText">
<p>We look forward to hearing from you! Please fill out the form below and we will get back with you as soon as possible.</p>
</div>
<div class="form-group">
<input class="form-control" placeholder="Name" id="IDFormField1_Name_0" name="formField_Name" value="" size="25" required="" type="text">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" id="IDFormField1_Email_0" name="formField_Email" value="" size="25" required="" type="email">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control bfh-phone" data-format="ddd ddd-dddd" placeholder="Phone" id="IDFormField1_Phone_0" name="formField_Phone" value="" size="25" type="tel">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Comments" name="formField_Comments" id="IDFormField1_Comments_0" cols="60" rows="5" required=""></textarea>
<span class="form-control-feedback"></span>
</div>
<div class="row submit-section">
<input name="submit" class="btn btn-success submit-button" value="Submit" type="submit">
</div>
</div>
$( "form" ).each(function() {
console.log( $(this)[0] );
sCurrentOnSubmit = $(this)[0].onsubmit;
$(this)[0].onsubmit = null;
console.log( $(this)[0] );
$( this )[0].onsubmit( function() {
console.log( 'test' );
});
});
You should be able to add unobtrusively another onsubmit function to #myForm, in addition to the function which already executes:
function myFunction() {
...
}
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',myFunction,false);
Try
$("#myForm").submit(function(){
.. Your stuff..
console.log("submit");
return false;
});
This will trigger everytime the form is submitted then the end return false stops the forms default actions from continuing.
Try this, it is plain Javascript:
function overrideFunction(){
console.log('Overrided!');
}
var form;
form = document.querySelector('#myForm');
form.setAttribute('onsubmit','overrideFunction()');
Regards.
You should trigger a change event on every field in the form to check on validation.
$('input').on('change', function(e) {
if($(this).val() == '') {
console.log('empty');
}
});
This wil help the user mutch faster then waiting for the submit.
You could also try a click event before the submit.
$('#formsubmitbutton').on('click', function(e) {
//your before submit logic
$('#form').trigger('customSubmit');
});
$('#form').on('customSubmit', function(e) {
//your normal submit
});
Try this code:
$("#myForm").on('submit',function() {
console.log("hi");
});
Stumbling across this post and putting together other javascript ways to modify html, I thought I would add this to the pile as what I consider a simpler solution that's more straight forward.
document.getElementById("yourFormID").setAttribute("onsubmit", "yourFunction('text','" + Variable + "');");
<form id="yourFormID" onsubmit="">
....
</form>
I am trying to place 2 HTML forms on the same page, then use JavaScript to control the target .php file they submit to, based on which submit button is pressed.
At the moment, it's sending to the correct php/email address, but also taking the user away from the page - which is what I want to prevent.
Any help would be appreciated. Here is my HTML:
<div class="col-md-6">
<form class="form" id="ajax-contact-form" action="multi/sendmail.php">
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-user"></i></span>
<input type="text" name="contact_name" id="contact_name" class="form-control" placeholder="Name" required>
</div>
</div>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-envelope"></i></span>
<input name="contact_email" id="contact_email" type="email" class="form-control" placeholder="Email" required>
</div>
</div>
<textarea name="contact_message" id="contact_message" placeholder="Message" rows="8" class="form-control" required></textarea>
<div class="controls send">
<button type="submit" class="btn-primary btn-lg" value="Submit1" id="submit2" onClick="mainform">Send</button>
<div class="loading"></div>
<div class="results"></div>
</div>
</form>
</div>
<!--FORM 2-->
<div class="col-md-6">
<form class="form2" id="ajax-contact-form2" action="multi/sendmail2.php">
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-user"></i></span>
<input type="text" name="contact_name" id="contact_name" class="form-control" placeholder="Name" required>
</div>
</div>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-envelope"></i></span>
<input name="contact_email" id="contact_email" type="email" class="form-control" placeholder="Email" required>
</div>
</div>
<textarea name="contact_message" id="contact_message" placeholder="Message" rows="8" class="form-control" required></textarea>
<div class="controls send">
<button type="submit" class="btn-primary btn-lg" value="Submit2" id="submit2" onClick="form2">Send</button>
<div class="loading"></div>
<div class="results"></div>
</div>
</form>
</div>
<!--/FORM 2-->
And here is my JavaScript:
function mainform() {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail.php', $('.form').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
}
function form2() {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
}
And here is my old JavaScript, which worked:
$('form').submit(function(e) {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail.php', $('.form').serialize(), function(data){
$('.results').html(data);
}).success(function(){
$('.loading').hide();
})
})
And one of the PHP files:
<?php
$name = isset($_REQUEST['contact_name']) ? $_REQUEST['contact_name'] : '' ;
$email = isset($_REQUEST['contact_email']) ? $_REQUEST['contact_email'] : '' ;
$message = isset($_REQUEST['contact_message']) ? $_REQUEST['contact_message'] : '' ;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From:".$name." ".$email;
// Replace mail#website.com with your email
mail( "me#email.com", "Message from My Future Now Website",$message, $headers );
print "<strong>Form submitted successfully.</strong>";
?>
What am I doing wrong?
Have you tried changing the second place that the following lines appears to something else?
<div class="loading"></div>
<div class="results"></div>
I see both javascript functions refer to an element like it's the only one, and you have two now. If you change the second one to this:
<div class="results2"></div>
<div class="loading2"></div>
Then you can change
function form2(){
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data){
$('.results').html(data);
}).success(function(){
$('.loading').hide();
})
}
to:
function form2(){
e.preventDefault();
$('.loading2').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data){
$('.results2').html(data);
}).success(function(){
$('.loading2').hide();
})
}
I think that will give you greater success. Let me know if you run into any further problems after trying such a change
There are several problems here which are preventing the functionality you want.
Your page is posting because when you call e.preventDefault() - I suspect you are getting a JavaScript error, indicating that e is undefined.
Because the default behavior of a submit button being clicked is therefore not being prevented - it occurs... and the default behavior is a full-page post to the server. This is why you're being taken away from your page.
There are 2 ways you can solve for this easily:
1. Solution 1: Just add the event parameter back in
function mainform(e) { ... }
function form2(e) { ... }
This will simply fix the JavaScript error you currently have, and allow your e.preventDefault() to work.
However - you are using jQuery on your page already - so I suggest that you maintain consistency with your tools - and use jQuery's event binding syntax. This is how your original JavaScript was written - and you can now go back to it.
2. Solution 2: Reintroduce jQuery
Change the ID of your your first form's submit button to ID="submit1'. Currently both buttons have the same name, which is invalid HTML and may cause issues.
Remove the onclick= binding syntax from both button elements.
Update your JavaScript as follows:
New JavaScript:
$('#submit1').on('click', function (e) {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail.php', $('.form').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
});
$('#submit2').on('click', function (e) {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
});
Note that we still added back in the e to each function() call - exactly as in Solution 1.
If this doesn't work for you - feel free to comment and ask for more help.