open bootstrap modal from script in another page in php - javascript

in my application there is an inquiry form. My task is when i submit the inquiry form it send an email and if email is sent successfully I have to show a success message in a modal. I am writing my sendemail code inside index.class.php file. I have to show the modal in services.php file. How can I do that. I tried it by header location but it doesn't work. I didnt know whether it was right or not.
Here is my code:
index.class.php
case "submitservceEnquiryMedical":
$mcpage = "services.php";
if($this->sendMedicalservceenquiryEmail()) {
$flmsg="success";
}
else {
$flmsg="fail";
}
header("Location: services.php?flMsg=$flmsg");
exit();
break;
Services.php
if(!EMPTY($_REQUEST['flmsg']))
{
$flmsg=$_GET['flmsg'];
if($flmsg=='success')
{
echo '<script> $("#Service-Enquiry").modal("show"); </script>';
}
else{
echo '<script> $("#Service-Enquiry").modal("show"); </script>';
}
}
<div class="modal fade" id="modal-success">
<div class="modal-dialog">
<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>
<h4 class="modal-title">Success</h4>
</div>
<div class="modal-body">
<p>You have succesfully submitted</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Can anyone please help me

In my opinion here there are differents problems you can't use header location in that way and you are doing javascript injection inside php that really in this case no need.
My solution, or better what i do in my site it's this:
I do an ajax call to the PHP method(page, function, method it's the same), that sends the email, passing all the value from ajax and print an answer to the client/ajax in case the mail was sent or not...so OK or KO(in my case 00 is OK) and in the success of the ajax call i manage the answer 00 so ok etc....In your way you must do an ajax call to this
sendMedicalservceenquiryEmail()
Return the flag and after in ajax at the success, if flag is success then modal show...I try to attach you my code if can be of help, just to look the architecture.
Code PHP where i do the ajax call, passing name, message, object of the email and destinatario is the recipient:
setlocale(LC_TIME, 'it_IT');//Settiamo il timezone per l'orario
date_default_timezone_set("Europe/Rome");
$data = date("d-m-Y");
$ora = date('G:i:A');
/**
* SESSION
*/
$datiUtente = $_SESSION['datiUtente'];
$utente = $datiUtente['username'];
$profilo = $datiUtente['profilo'];
$email = $_REQUEST['destinatario'];
$nome = $_REQUEST['nome'];
$to = $email;
$messaggio = trim($_REQUEST['messaggio']);
$oggetto = trim($_REQUEST['oggetto']);
$mittente = 'YOUR ACCOUNT#MAIL';
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$msg = '88'.'|';
$error='background: url("../img/error.png") no-repeat scroll left top #ffd0dc;
border: 1px solid #ac343d;
margin: 5px 0 15px;
padding: 5px 5px 5px 40px;';
$msg .= ("<div style='$error'>Formato Email non valido</div>");
$msg = str_replace('\n', '', $msg);
$msg = str_replace('\r', '', $msg);
print $msg;
exit;
}
$message = "Email in arrivo da server <b>$mittente</b><br/>
Inviata da : <b>$nome </b><br/>
Profilo utenza : <b>$profilo </b><br/><br/><br/>
$messaggio ";
$subject = $oggetto;
$menof = "'-f" . trim($mittente) . "'";
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
$eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
$eol="\r";
} else {
$eol="\n";
}
$now = rand();
$headers = 'From: YOUR NOME YOURSURNAME<YOUR ACCOUNT MAIL>'.$eol;
$headers .= 'Reply-To: YOUR NOME YOURSURNAME<YOUR ACCOUNT MAIL>'.$eol;
$headers .= 'Return-Path: YOUR NOME YOURSURNAME<YOUR ACCOUNT MAIL>'.$eol; //risposta a...
$headers .= "Message-ID:<".$now." TheSystem#".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; //Per non andare nello spam
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: text/html; boundary=\"".$mime_boundary."\"".$eol;
if (mail(trim($to), trim($subject), wordwrap(trim($message)), trim($headers),trim($menof))){
$msg = '00'.'|';
$msg .= ("L'email è stata inviata correttamente");
$msg = str_replace('\n', '', $msg);
$msg = str_replace('\r', '', $msg);
print $msg;
exit;
}
else{
$msg = '99'.'|';
$msg .= ("Invio Email FALLITO!!!");
$msg = str_replace('\n', '', $msg);
$msg = str_replace('\r', '', $msg);
print $msg;
exit;
}
At the click of the button send mail i invoke this function that does the call at the php over
function inviaEmailCliente(){
var nome = $('#nomeMail').val();
var messaggio = $('#messaggioMail').val();
var oggetto = $('#oggettoMail').val();
var destinatario = $('#destinatarioMail').val();
if (oggetto == false){
$('#contenutoInserimentoAna').html('Oggetto Obbligatorio');
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
return;
}
if (messaggio == false){
$('#contenutoInserimentoAna').html('Messaggio Obbligatorio');
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
return;
}
if (nome == false){
$('#contenutoInserimentoAna').html('Nome Obbligatorio');
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
return;
}
$.ajax({
type: "POST",
url: "../index.php",
dataType: "html",
data : { azione : 'inviaEmailCliente',
messaggio : messaggio,
oggetto : oggetto,
destinatario : destinatario,
nome : nome },
success:function(data){
dati = data.replace(/(\r\n|\n|\r)/gm,"");
if (dati.length > 0){
dati = dati.split('|');
if (dati[0] == '00'){
$('#contenutoInserimentoAna').html(dati[1]);
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalAnagrafica').modal('hide');
$('#nomeMail').val('');
$('#messaggioMail').val('');
$('#oggettoMail').val('');
location.reload();
});
}
if (dati[0] == '88'){
$('#contenutoInserimentoAna').html(dati[1]);
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
}
if (dati[0] == '99'){
$('#contenutoInserimentoAna').html(dati[1]);
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalAnagrafica').modal('hide');
});
}
}
},
error:function (){
alert ('Errore di comunicazione con il server');
}
});
}
Html form of insert email, i don't paste the css...but hit is the form..
<input type="hidden" id="destinatarioMail" value="WRITE HERE THE ADRESS WHERE SENDS THE EMAIL{email} TO#EXAMPLE.COM" >
<div class="containerBorder padding3">
<div class="alert-warning">
<p><b>L'email sarà inviata a {email}</b></p>
</div>
<div class="row">
<div class="input-group">
<span class="input-group-addon testoBlu" id="nomeInvioMail">Nome *</span>
<input type="text" id="nomeMail" class="form-control" aria-describedby="nomeInvioMail" />
</div>
<div class="input-group">
<span class="input-group-addon testoBlu" id="oggettoInvioMail">Oggetto *</span>
<input type="text" id="oggettoMail" class="form-control" aria-describedby="oggettoInvioMail" />
</div>
<div class="input-group">
<span class="input-group-addon testoBlu" id="messaggioEmailCli">Messaggio Mail *</span>
<textarea class="form-control" id="messaggioMail" aria-describedby="messaggioEmailCli" style="max-width: 724px; max-height: 130px;"> </textarea>
</div>
</div>
<br>
<div align="center">
<input type="button" class="btn btn-danger" value="Invia" id="inviaEmailCli" onclick="inviaEmailCliente()" />
</div>
</div>
And this is the html for the modal
<div class="modal fade" id="modalAnagrafica" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabelAnagrafica">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary">
<h4 class="modal-title modalHeaderText" id="myModalLabelAnagrafica"><b>Anagrafica</b></h4>
</div>
<b><div class="modal-body" id="contenutoInserimentoAna">
</div></b>
<div class="modal-footer justify-content-center">
<div align="center">
<button class="btn btn-success btn-xs" data-dismiss="modal">Chiudi</button>
</div>
</div>
</div>
</div>
</div>

Related

Why my succes-msg or error-msg are not display?

well, in my js files, i'm trying to display success-ms or error-msg. I don't understang why my div #error-msg or #success-msg doesn't appear.
Here my js code. If user clicks on confirm, data are sent to process.php to insert the keyword in my mysql table
$(function()
{
$('#alert-change').click(function(event){
$("#error-msg12").html('');
$("#success-msg12").html('');
event.preventDefault();
$.post('include/process.php',$('#alert-change-form').serialize(),function(resp)
{
if (resp['status'] == true)
{
$("#success-msg12").html(resp['msg']+"");
$("#success-msg12").show();
}
else
{
var htm = '<button data-dismiss="alert" class="close" type="button">×</button>';
$.each(resp['msg'],function(index,val){
htm += val+" <br>";
});
$("#error-msg12").html(htm);
$("#error-msg12").show();
}
},'json');
});
});
My form
<div id="myModal_alert" class="modal fade">
<div class="modal-dialog modal-login1">
<div class="modal-content">
<form name="alert-change-form" id="alert-change-form" method="post">
<div class="modal-header">
<h4 class="modal-title">Add a keyword.</h4>
<div class="alert" id="error-msg12">
</div>
<div class="alert alert-success" id="success-msg12">
</div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="process" name="process" value="4">
<input type="hidden" id="first_name" value ="<?= $_SESSION['name']?>" class="form-control" name="first_name" minlength="3" maxlength="10" placeholder="" class="login" />
<div class="form-group">
<div class="clearfix">
<label>add a keywordt.</label>
</div>
<input type="text" id="kw" class="form-control" name="alert" placeholder="" class="kw" required />
</div>
</div>
<div class="modal-footer">
<button class="button btn btn-primary btn-large" id="alert-change">Confirmer</button>
</div>
</form>
</div>
</div>
</div>
and my process.php file
if ($_POST['process'] == '4') {
$error = array();
$res = array();
$success = "";
$alert = mysql_real_escape_string($_POST['alert']);
echo $_POST['first_name'];
echo $alert;
// errors
if (!preg_match("#^[a-z0-9_]+$#", $alert))
{
$error[] = 'error 1';
}
if (strlen($alert) < 2)
{
$error[] = 'error 2';
}
$sql = "SELECT * FROM users_alert WHERE user = :user AND kw = :alert";
$req = $bdd->prepare($sql);
$req->bindParam(':user', $_POST['first_name'], PDO::PARAM_STR);
$req->bindParam(':alert', $alert, PDO::PARAM_STR);
$req->execute();
$resultat = $req->fetchAll();
if (count($resultat))
{
$error[] = 'error 3';
}
if(count($error)>0)
{
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
// on exécute
$sqlQuery = "INSERT INTO users_alert (user,kw) VALUES (:user,:kw)";
$run = $bdd->prepare($sqlQuery);
$run->bindParam(':user', $_POST['first_name'], PDO::PARAM_STR);
$run->bindParam(':kw', $alert, PDO::PARAM_STR);
$run->execute();
$resp['msg'] = "success1";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
I've tried 4/5 things, in vain.
Somebody has an idea ?
Can you delete them in the process.php file and try again?
echo $_POST['first_name'];
echo $alert;
If this is not working, you should capture the post values ​​you sent to the process.php file and go step by step.

Bootstrap modal popup upon failed login

I have a login page (login.html) that calls a php with POST method to valid login credentials, which works just fine. If the email an password are incorrect, then in my current implementation, an alert pops up and the page reloads. I would like to know how to activate a modal instead of said popup.
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons"></i>
</div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body text-center">
<h4>Ooops!</h4>
<p>Something went wrong. File was not uploaded.</p>
<button class="btn btn-success" data-dismiss="modal">Try Again</button>
</div>
</div>
</div>
</div>
Complete PHP File:
<?php
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$conn = new mysqli('localhost','root','','rm');
if($conn->connect_error){
die('Connection Error: '.$conn->connect_error);
}
else{
$sql = "select * from superfan where email='".$email."' and password='".$pwd."' ";
$result = mysqli_query($conn,$sql);
$records = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if ($records==0)
{
echo '<script type="text/javascript">';
echo '$(document).ready(function() {';
echo '$("#myModal").modal("show");';
echo '});';
echo '</script>';
}
else
{
header('location:index.html');
}
mysqli_close($conn);
}
?>

How to send the drop down list value to an email? [duplicate]

This question already has an answer here:
How to send the selected value of a drop down menu to an email?
(1 answer)
Closed 4 years ago.
I have an question that I need to send selected drop down list value to an email.I already sent the other input values in the contact form to an email. But I do not know how to send the drop down list value to an email. Herewith attached the html, php and js code. Could anyone can help me?
Here is the html code
<!-- Contact form -->
<div class="modal fade" id="modalForm" role="dialog" style="width: 100%;">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name" style="border: 1px solid #fff; border-bottom: 1px solid #ccc;"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<label for="inputService">Service</label>
<select name="subject" class="form-control"
id="inputService" size="1">
<option value="Option1">Pr-Matrimonial Services</option>
<option value="Option2">Extra Marital Affairs</option>
<option value="Option3">Divorce Case Support</option>
</select>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JS code...
<script>
function submitContactForm(){
var usernameRegex = /^[a-zA-Z0-9]+$/;
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(name.trim() != '' && !usernameRegex.test(name)){
alert('Please enter valid name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'contact.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
php code...
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$option= $_POST["subject"];
/*
* Send email to admin
*/
$to = 'support#ribelz.net';
$subject= 'Contact Request of privateeyelk.com';
$htmlContent = '
<h4>Contact request from : '.$email.'</h4>
<p>Name: '.$name.'</p>
<p>Email: '.$email.'</p>
<p>Message: '.$message.'</p>
<p>Service: '. $option.'</p>
';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: Private Eye<privateeyelk.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
You didn't retrieve the value of select in your Js code
Try adding this line in your submitContactForm function
var subject = $('#inputService').val();
Please check this line to
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message+'&service='+subject,

Preventing bootstrap modal from disappearing in case validation failure using PHP after submit button is clicked

My question is how do I stop modal from closing, on two occasions, when user clicks the sign up button:
if the inputs are invalid? and display PHP error message
inputs are valid and to display PHP success message for couple of seconds before closing modal?
for the first case if I reopen the modal I can see the validation error messages which are displayed by PHP.
I have checked this similar question but haven't figure it out how to do it in my case yet so any help will be much appreciated. I would like to fully understand what is going on and what I am doing.
So far after reading here and there I noticed that this can probably be achieved by:
JQuery / JavaScript to do the form validation and not to use PHP
some people suggested using iframe
Is there a way to use the PHP code below and display error / success messages from this code? or it has to be done via JQuery/JS?
My PHP with HTML code
<?php
ob_start();
include('header.php');
include_once("db files/db_connect.php");
if(isset($_SESSION['user_id'])) {
header("Location: index.php");
}
$error = false;
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$uname_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success_message = "Successfully Registered!";
} else {
$error_message = "Error in registering...Please try again later!";
}
}
}
?>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="registrationFormLabel" 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="registrationFormLabel">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- REGISTRATION FORM -->
<div class="container">
<div class="form-row">
<div class="col">
<form onsubmit="return validateForm()" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<fieldset>
<legend>Sign Up</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($uname_error)) echo $uname_error; ?></span>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Password" required class="form-control" />
<span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
</div>
<div class="form-group">
<label for="name">Confirm Password</label>
<input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
<div class="form-group text-center">
<input id="modalSubmit" type="submit" name="signup" value="Sign Up" class="btn btn-primary" formnovalidate />
</div>
</fieldset>
</form>
<span class="text-success"><?php if (isset($success_message)) { echo $success_message; } ?></span>
<span class="text-danger"><?php if (isset($error_message)) { echo $error_message; } ?></span>
</div><!-- / col -->
</div><!-- / form-row -->
<!-- already registered row -->
<div class="row">
<div class="col text-center">
Already Registered? Login Here
</div>
</div> <!-- / already registered row -->
</div><!-- / REGISTRATION FORM container-->
</div><!-- / Modal body div -->
</div>
</div>
</div><!-- / Modal -->
My modal opens when the user clicks the button on index page and here is the JQuery code
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
});
});
Add below PHP script after end of document (/html) before script tag
<?php
if ($error) {
echo '<script>$("#myModal").modal("show");</script>';
} else {
echo '<script>$("#myModal").modal("hide");</script>';
}
?>
Invalid:
You can stop the submit button from submitting if the inputs are invalid.
To stop submit use the code
$(':input[type="submit"]').prop('disabled', true);
To show modal
$("#myModal").modal('show');
To enable submit again, when modal is closed due to error, use the code
(You will want to enable it again so the user can try again)
$("#myModal").on('hidden.bs.modal', function (e) {
$(':input[type="submit"]').prop('disabled', false);
});
For the validation I would do it this way (add a success variable):
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success = 1;
} else {
$success = 2;
}
And then call it like this:
<?php if($success == 1){ ?>
<script>
$(document).ready(function() {
$("#yoursuccessmodal").modal('show');
});
</script> <?php } ?>
You can then choose to add a fade to it, or have the user click it away.
The modal will then show AFTER the submition has been sent.
This better work, as I have used it this way in my project as well and it works like a charm for me.

I want to use a modal to send mail, via a php file and I want the pop closed once submit is closed

I have a simple form that loads nicely via bootstrap modal once the page loads. I want to process and send the once I click submit and the modal should close immediately without refreshing the page. Below are my codes. It is not working. Please I need help. With a php file it sends the mail but it takes me to the php file and gets stuck there. I believe it's a small thing but I can't wrap my head around it.
$(function() {
$(window).load(function() {
$('#Modal').modal('show');
});
$('#btn_send').click(function(){
var name = $(":input[name='name']").val();
var email = $(":input[name='email']").val();
var varData = 'name=' + name + '&email=' +email;
$.ajax({
type: 'POST',
url: 'index.php',
data: varData,
success: function(){
alert('Mail sent. Thank you.');
}
});
});
});
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="form_pp">
<div id="Modal" class="modal fade in" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<div class="modal-header" style="margin-top:120px;">
<div class="modal-body">
<div class="form-group">
<input class="form-control" placeholder="YOUR FULL NAME" name="name" type="text" required autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="YOUR EMAIL ADDRESS" name="email" type="email" required>
</div>
<br>
<button type="submit" class="btn btn-default" style="color:#c13b01" id="btn_send">SEND</button>
<button type="button" class="btn btn-default" style="color:#c13b01" name="send" id="btn_cancel" data-dismiss="modal">CANCEL</button>
</div>
</div>
</div>
</div>
</div>
php file
if (isset($_POST['name']) && isset($_POST('email))) {
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "Results from Online contact form:\n\n";
$email_from = $email;
$email_to = 'mail#mail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email. "\n\n" . 'Subject: ' . $subject;
#mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
}
Leandro's answer is part of your success. I would say that the reason the php script isn't working, is because it doens't get any data submited and therefor can't send an email
In order to retrieve the data from both the name as well as the email you need to change the part where it says
var name = $("name").val();
var email = $("recipientmail#mail.com").val();
to
var name = $(":input[name='name']").val();
var email = $(":input[name='email']").val();
That should help you to get your data over to the server.
with the help of #Eric Dohmen, I figured I missed out quotes and the correct block parenthesis for the email variable. Here it is:
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "Results from Online contact form:\n\n";
$email_from = $email;
$email_to = 'mail#mail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email. "\n\n" . 'Subject: ' . $subject;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
}
else{
echo alert('Message did not send');
}

Categories

Resources