Prevent modal from closing when submiting form - javascript

I have a form inside a modal, I want to prevent the modal from closing and refreshing the page after submiting the form if there's errors on some fields and show error messages inside the modal, if everything is okay the modal shoud submit the form and refresh the page.
This is my code :
<div class="modal fade" id="addTeam">
<div class="modal-dialog rap-modal-thumb">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button>
<h4 class="modal-title" id="myModalLabel">Add team</h4>
</div>
<div class="modal-body"><br>
<div class="page-wrap">
<form action= "<?php echo $action; ?>" enctype="multipart/form-data" method="post">
<div class="container">
<div class="row">
<div class="input-group input-group-icon">
<div class="col-third input-group-icon">
<input type="text" id="name" name="name" placeholder="Nom*" required="required">
<div class="input-icon"><i class="fa fa-users"></i></div>
</div>
<div class="col-third input-group-icon">
<input type="text" id="abreviation" name="abreviation" placeholder="Abréviation*" required="required">
<div class="input-icon"><i class="fa fa-flag-o"></i></div>
</div>
<br>
* Required fields
<br><br>
<?php
if (isset($error))
echo '<div style="color:#fff;" class="alert bg-danger" role="alert"><em class="fa fa-lg fa-warning"> </em>',$erreur,'</div>';
?>
<button type="submit" id="addTeam" name="addTeam" class="btn btn-primary">Ajouter</button>
</div>
</form>
</div>
<br>
</div>
</div>
</div>
In php if for example the name of the team is less than 6 characters then show the error message inside the modal without closing it. In my case here the message appear after the page is refreshed and the show button of the modal is clicked again.
if (isset($_POST['addTeam'])) {
$name= $_POST['name'];
if (strlen($name)<3){
$error = 'Name must be atleast 6 characters';
}
else{
$action = "uploadTeam.php";
}
}
Anyway to do that ?

If your form is submited by default by the browser, it'll auto-refresh the page (to create a new HTTP POST request to the server)
You have to use AJAX to call the server on background and avoid reloading the content:
// Create an event listener to catch "when the form is submited"
$('.modal-body form').submit(function(event) {
// to stop the form from submitting (and the page reloading, so the modal will not close)
event.preventDefault();
// Call server manually and send form data (see Mikey's comment)
$.post('my.url.com/file.php', $(this).serialize(), function(err, result) {
if (err) {
// Display error on form
} else {
// Success... Redirect ?
window.location = 'my.new.url/path.html'
}
})
});

You will need to override some client behavior for this. In fact, it will be easier for you to do your validation all on the client side (if possible). Override the form's default behavior, validate, and then return true or false based on the results of your validation function:
<script>
$('form').on('submit', function(e) {
if (validate()) { //your validation function here
return true;
}
return false;
});
function validate() {
if (!$('input[name=name]').val() || $('input[name=name]').val().length < 3) {
return false;
}
return true;
}
</script>

Related

Display registration errors from php array into modal

I'm trying to make a registration form using bootstrap and PHP and post the errors in a modal. (Incorrent password/Invalid email address etc.) All error is put into an array. My problem is that I don't know how to take the array and use it in the HTML, and call the modal from there. Also, I don't want the page to refresh after I click on the "register button".
I've already tried from the below links but without success.
Button click not firing in modal window (Bootstrap)
How to open the modal if there is a validation error?
This is the form from the file Register_login.php
Register_login.php
<div class="container form_container_register w-100 mt-1">
<form method="post" action="Register_login_route.php" data-toggle="modal">
<div class="form-group">
<label for="inputEmailRegister">Email adress</label>
<input type="email" class="form-control" id="inputEmailRegister" name="inputEmailRegister" aria-descridedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="inputPasswordRegister">Password</label>
<input type="password" class="form-control" id="inputPasswordRegister" name="inputPasswordRegister" placeholder="Enter password">
</div>
<div class="form-group">
<label for="rePasswordRegister">Retype password</label>
<input type="password" class="form-control" id="rePasswordRegister" name="rePasswordRegister" placeholder="Retype password">
</div>
<div class="container register_buttons_container w-100 justify-content-center align-items-center d-flex">
<button type="submit" name="reg_button" id="reg_button_id" value="Register" data-toggle="modal" data-target="#exampleModalCenter" class="register_btn btn w-50">Register</button>
</div>
</form>
</div>
and the modal from the boostrap page: (is this the correct place to put it)?
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Register_login_route.php
$errors is the array where I store the error messages. I posted only what I do with that array. How can I use the session variable in the first PHP file? There is no problem with the PHP code. $session_start() is placed in both files, the problem is with displaying the modal
if (count($errors) == 0) {
$insertPass = md5($password);
$insertQuery = "INSERT INTO physical_users (email, password) VALUES (:email,:password)";
$stmt = $conn->prepare($insertQuery);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":password", $insertPass);
$result = $stmt->execute();
} else{
$_SESSION['errors'] = $errors;
header("location: Register_login.php");
}
I tried the solutions from the links above with the js but no success
You can use jQuery AJAX to send a request with form data to your back end function and do the validation, return errors from there. Then you can print them out in your success function. In that case you won't need a form tag since it automatically refreshes the page. Just take the values of your inputs and send them in your AJAX call in the data field.
Example of an AJAX call:
$.ajax({
url: "your_php_file_name.php",
type: "POST",
dataType: "json",
data: {action:"myAction",email:someEmail,password:somePassword},
success: function(res){
console.log(res);
}
})
And your PHP code should look like this:
if(isset($_POST["action"])){
if($_POST["action"] == "myAction"){
$email = $_POST["email"];
$password = $_POST["password"];
// Example of validation
if(strlen($password) < 6){
print "Password too short";
// Printing anything will return the printed value to the success function of your AJAX call and you can work with it. If you want to return an array instead of a string you can do `print(json_encode($array))`
}
}
}
To call your modal you just need to write $('#myModal').modal() inside of your success function and display your errors in it. Hope this was helpful. If you have any questions leave a comment.
1.) Get the errors on the page. You can do this by printing it as a JavaScript variable on the page. Something like `
<script>var errorList = <?php echo json_encode($errors);>?; </script>`
2.) On the page, using JavaScript, check the errorList variable. If it has stuff in it, then invoke the bootstrap modal and show them. Something like
<script>
$(document).ready(function(){
if(errorList.length > 0){
//Put the errors in the .modal-content element
$("#exampleModalCenter .modal-content").text(errorList.join(","));
//Show the modal
$("#exampleModalCenter").modal("show");
}
})
</script>
that's a rough draft--spat out as i wrote this--but it should set you on the right path.

Validate a form element without/before submitting the form with JavaScript

I have an HTML form that has its elements displayed in various Bootstrap modals. The first modal has a text box input that and a "Next" button to open the next modal. When the "next" button is pressed. I want to check if the text box is empty, and trigger a validation message. The form does not get submitted until the very end. Everything I've tried has not worked so far.
Javascript/jQuery code
$("#add_assistant_next").click(function () {
var textInput = document.getElementById('add_assistant_user');
var text = textInput.value;
if (text === "") {
textInput.setCustomValidity('Please fill out this field.');
textInput.checkValidity();
var form = $('#form_add_assistant');
form.find(':submit').click();
} else {
textInput.setCustomValidity('');
}
});
HTML
<form name="add_assistant" method="post" id="form_add_assistant">
<div class="modal-body">
<div class="step">
<span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
</div>
<div class="pl-3 pt-1">
<div>
<input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
<button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
</div>
<input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
</div>
</div>
... form continues in other modals
Your JS code is probably fighting with Bootstrap for control of that button. To get around that, and have your validation, you could try modifying your code to have a middle step / temporary button to help with validation first before actually submitting. So something like this:
Javascript/jQuery code
$("#my_temp_button").click(function () {
var textInput = document.getElementById('add_assistant_user');
var text = textInput.value;
// Might also want to handle null and undefined cases?
if (text === "" || text === undefined || text === null) {
// I'm assuming if it's empty, it doesn't pass validation,
// so we just display this warning and wait for the user to fix it:
textInput.setCustomValidity('Please fill out this field.');
} else {
// it's not empty so validate:
if (textInput.checkValidity()) {
// it passed validation, so ok to submit.
// call the real button:
$('#add_assistant_next').click();
// do you need this?
var form = $('#form_add_assistant');
form.find(':submit').click();
} else {
// it failed validation, so display another error?
textInput.setCustomValidity('Try again.');
}
}
});
HTML:
<form name="add_assistant" method="post" id="form_add_assistant">
<div class="modal-body">
<div class="step">
<span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
</div>
<div class="pl-3 pt-1">
<div>
<input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
<!-- Feel free to change the id name. This is the button the user sees. It's only purpose is to give your function above full control to it and prevent Bootstrap from touching it and jumping to the next modal without having the user fix the validation failure first: -->
<button type="button" id="my_temp_button" class="btn btn-outline-secondary btn">Look up user</button>
<!-- Hide the real button from the user: -->
<div style="display:none">
<button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
</div>
</div>
<input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
</div>
</div>
...
Have you tried adding a trap for the submit event itself?
$('#form_add_assistant').submit(function(evt){
//do your validation here
if (validation fails){
return false; // OR, alternatively, `evt.preventDefault()`
}
//form submission will continue if not returned false
});
References:
https://api.jquery.com/submit/
How to conduct manual form validation via jQuery .submit()

Logging in via modal using AJAX and PHP

to be fair, I'm fairly new in the AJAX area (newbie to be more precise) and i think that i took quite a large bite entering that field.So, I'm struggling for a several days now trying to implement AJAX with my PHP script. Before you flag this question as duplicate please consider that I've tried every posted question from this site and not one solution pop out. That being said, here is what I want to achieve: I want to show some sort of message after PHP script was successful or unsuccessful, something like picture below:
If there was successful show me msg, and redirect me (after 2 sec) to admin site, and if not show me error!
So, here is code for modal form:
<div class="modal fade" id="test" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">test</h4>
</div>
<div class="modal-body">
<form id="myform" method="POST" role="form">
<div class="form-group">
<label for="user">User:</label>
<input name="user" type="text" class="form-control" placeholder="Unesi korisnika">
</div>
<div class="form-group">
<label for="pass">Password:</label>
<input name="pass" type="password" class="form-control" placeholder="Unesi lozinku">
</div>
<div id="error">
<div class="alert alert-danger"> <strong>Error, try again!</strong> </div>
</div>
<div id="thanks">
<div class="alert alert-success"> <strong>Logging in..</strong></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="reset" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" id="submitForm">Login!</button>
</form>
</div>
Here is my javascript block of code: Here I tried loging in using my php script but nothing happens, it's only showing me #thanks div when I start typing
$('#test').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$(':input', '#myform').val("");
});
$("#thanks").hide();
$("#error").hide();
$("#myform").click(function (e) {
var url = "login.php";
$.ajax({
type: "POST",
url: url,
data: $('#myform').serialize(),
success:
$("#thanks").show(),
error: function () {
$("#error").show();
}
});
e.preventDefault();
});
Here is my PHP doLogin() function inside myAuth class:
static function doLogin() {
if(
!empty($_POST['user'])
&&
!empty($_POST['pass'])
) {
if(!session_id()) session_start();
// check and retrive user with sended pass
$user = self::_fetchUserWithPassDB();
// if user found log in
if($user) {
// security
$token = md5(rand(100000,999999));
// save token in session
$_SESSION["auth"] = $token;
// save user in session
$_SESSION["user"] = $user[0]["user"];
// save role in session
$_SESSION["role"] = $user[0]["role"];
// postavi validity and token in cookie, session in base
self::_setCookieSessionDBTokenValidity();
// redirect on admin.php
header( "refresh:2;url=admin.php" );
}
else {
header('Location:index.php');
}
if(!$user) {
header("refresh:1;url=index.php" );
}
} // od if POST
and finally here is my login.php
<?php
// login.php
require_once('init.php');
myAuth::doLogin();
?>
Is it problem in in doLogin() function or is there problem with javascript, I really don't know? If there is any help, when I use this script without AJAX it works normal without any problems.
Like this:
<form action="login.php" id="myform" method="POST" role="form">
....<!--rest of the modal form-->
UPDATE 1.
I've tried something like this, but it does not work. Also, I've removed redirect from doLogin () and added in AJAX call but without any luck
$("#myform").submit(function(e) {
var url = "login.php";
$.ajax({
type: "POST",
url: url,
data: $('#myform').serialize(),
success: function() {
$("#thanks").show(), setTimeout(function() {
window.location.href = "admin.php";
}, 2000);
},
error: function() {
$("#error").show();
}
});
e.preventDefault();
});
Try moving
<form id="myform" method="POST" role="form">
outside of
<div class="modal fade" id="test" role="dialog">
i.e.
<form id="myform" method="POST" role="form">
<div class="modal fade" id="test" role="dialog">
...
</div>
</form>
Currently, your HTML is not valid (the start of <form ... lies inside <div class="modal-body"> but the end of it is after the modal-body has ended. Your browser is probably cutting off the <form at the end of modal-body to follow valid HTML.

is there a way to prevent a form from submitting if I click "cancel" from the js confirm script that went before it?

I used the modal class in bootstrap, thru POST action to delete a record from the table, but it didn't have any confirmation to it so i tried using this confirm javascript.
The confirm works. The problem now is, even if I select "cancel" from the js confirm dialog box, it still deletes or routes to the delete.php file (which deletes the record) :o
Question: is there a way to prevent the form from submitting if I click "cancel" from the js confirm script? Thanks!
<!-- script and modal FROM THE HTML page users.php -->
<script>
function iconfirm() {
var r = confirm("Do you really want to delete this user? Press ok to confirm.");
if (r==true)
{
window.location="postDeleteUser.php";
return true;
}
else
{
alert("You pressed Cancel!");
window.location="users.php"
}
}
</script>
<div id="modDeleteUser" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modAddUser">
<div class="modal-dialog bs-example-modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 id="modAddUser">Delete User</h3>
</div>
<div class="modal-body">
<form class="" action="postDeleteUser.php" method="post">
<div class="control-group">
<label class="control-label" for="inputID">Input the User ID of the user you are deleting:</label>
<div class="controls">
<input type="text" class="input-small" id="inputID" placeholder="- ID No. -" name="txtuserid">
</div>
</div>
<!--<button type="submit">OK</button>-->
<button onclick="iconfirm()" type="submit">OK</button>
<!--======================-->
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</div>
</div>
<!-- FROM THE HTML page end -->
//=================== Delete.php start =========== //
<?php
$db_name="homeis";
$tbl_name="users";
$user_id=$_POST["txtuserid"];
include ("connect.php");
$deleteQuery= "DELETE FROM $tbl_name WHERE id='$user_id'";
$result = mysqli_query($db,$deleteQuery);
if ($db->query($deleteQuery) === true) {
echo "<script>alert('Data deleted!');window.location.href='users.php'</script>";
}
else {
echo "<script>alert('Unable to delete. Please try again.');window.location.href='users.php'</script>" . $conn->error;
}
$db->close();
?>
//=================== Delete.php end =========== //
You need to return false if you don't want the thing submitted..
add "return" here
<button onclick="return iconfirm()" type="submit">OK</button>
Then return something in the function. if you return true it will submit. if you return false, your computer might explode or something idk try it.
function iconfirm() {
var r = confirm("Do you really want to delete this user? Press ok to confirm.");
if (r==true)
{
window.location="postDeleteUser.php";
return true;
}
else
{
alert("You pressed Cancel!");
window.location="users.php"
// return false here
return false;
}
}
However, it might be easier to just..
<button onclick="return confirm('are you sure about whatever it is youre doing?')" type="submit">OK</button>

PHP/Javascript - Check in JS if PHP file upload was successful

there. I have a page that makes a form containing file upload in a Bootstrap Modal.
The submit of the form is made on Javascript and I need to get a message about the file upload to show to the user before reloading the page. Here is the example:
HTML:
<div id="modal-insert-occurrence-form" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="modal-insert-occurrence-label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="modal-insert-occurrence-label">Insert occurrence</h3>
</div>
<div class="modal-body">
<form id="insert-occurrence-form">
<fieldset>
<label for="obs-occurrence">Obs</label>
<textarea name="obs-occurrence" id="obs-occurrence" rows=3 class="span4"></textarea>
<label for="image-occurrence">Screenshot</label>
<input type="file" name="image-occurrence" id="image-occurrence" />
</fieldset>
</form>
</div>
<div class="modal-footer">
<button id="modal-insert-occurrence-submit" class="btn btn-info" onClick="fileUp('insert-occurrence-form','ajax/upload.php');" >Insert</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</div>
JavaScript:
function fileUp(form_id, action_url) {
var form = document.getElementById(form_id);
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
form.submit();
//Need to show the message here!
location.reload();
}
What can I do? Thanks.
Basically... you can't "Check in JS if PHP file upload was successful". Js is client side, php is server side.
What you can do, since you already reload the page on form submission, is to check in php if the file was uploaded, and set a var in js with the answer. Something like:
<script>
var uploaded = <?php echo $uploadSuccess; ?>;
</script>
But that's kind of messed up. A cleaner solution would be to send an ajax request to check.

Categories