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.
Related
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>
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 am using this code to request new user to change his password on first login. So here is my form which opens in a popup after first login:
<div class="modal" id="change-password-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg" role="document" style="top:20%">
<div class="modal-content content-align">
<div class="modal-header">
<h3 class="modal-title text-center modal-title-col">Change your password</h3>
</div>
<div class="modal-body">
<form id="change-password" class="ns-form half-width" method="post" action="/profile/changepassword">
<?php if(empty($_POST) || isset($exc)): ?>
<label>
<input class="input-box" type="password" name="curr_pwd" required="required" maxlength="64" placeholder="Current Password" required="required" />
<?php if(isset($exc) && $exc->getCode() == eInfo::INVALID_CREDENTIALS): ?>
<span class="error msg-block bottom">
<?php echo stripslashes($exc->getMessage()); ?>
</span>
<?php endif; ?>
</label>
<label>
<input class="input-box" type="password" name="new_pwd" required="required" maxlength="64" placeholder="New Password" />
<?php if(isset($exc) && $exc->getCode() == eInfo::INVALID_PASSWORD): ?>
<span class="error msg-block bottom">
<?php echo stripslashes($exc->getMessage()); ?>
</span>
<?php endif; ?>
</label>
<label>
<input class="input-box" type="password" name="retype_pwd"
required="required" maxlength="64" placeholder="Re-type Password" />
</label>
<center> <input type="submit" value="Change" class="change-button" id="change-button" /> </center>
<?php endif; ?>
</form>
<?php if(!empty($_POST) && !isset($exc) && isset($message)): ?>
<br/>
<strong><?php echo $message; ?></strong>
<br/>
<center>Go home</center>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
When i click on submit function it takes me to profile/changepassword which i have written in action. I want my form to submit in the popup only not to redirect to other page.
profile/changepassword function in controller
public function changepassword() {
User::authenticate();
$this->log->debug("Inside " . __METHOD__ . "()...");
$this->template->title = 'ChangePassword - '.TITLE_SUFFIX;
if(!empty($_POST)) {
try {
$allowed = array('curr_pwd', 'new_pwd', 'retype_pwd');
if($allowed != array_keys($_POST)) {
loadException('InvalidFormSubmissionException');
throw new \InvalidFormSubmissionException();
}
User::validatePassword($_POST['new_pwd']);
if($_POST['new_pwd'] !== $_POST['retype_pwd'])
throw new model\exceptions\user\InvalidPasswordException('Passwords do not match!');
if($_POST['curr_pwd'] === $_POST['new_pwd'])
throw new model\exceptions\user\InvalidPasswordException('Current password and new password should not be same!');
$userService = new model\UserService();
if(!($user = $userService->verifyPasswordForUser($_SESSION['userId'], $_POST['curr_pwd']))) {
loadException('user/InvalidCredentialsException');
throw new model\exceptions\user\InvalidCredentialsException('Wrong password!');
}
/*var $user User */
$user->setPassword(md5($_POST['new_pwd']));
$user->getPwdUpdated(1);
$_SESSION['pwd_updated']=1;
$userService->update($user);
$this->template->message = 'Your password has been changed.';
} catch(model\exceptions\user\InvalidCredentialsException $e) {
$this->log->debug($e->getMessage());
$this->template->exc =$e;
} catch (\InvalidFormSubmissionException $e) {
$this->log->debug($e->getMessage());
$this->template->exc = $e;
} catch(model\exceptions\user\InvalidPasswordException $e) {
$this->log->debug($e->getMessage());
$this->template->exc = $e;
} catch(\Exception $e) {
$this->log->debug($e->getMessage());
$this->template->exc = $e;
}
}
$this->log->debug("Peak memory usage in " . __METHOD__ . " = " . (memory_get_peak_usage(TRUE) / 1024) . " KB");
$this->template->setLayout('profile');
$this->template->show();
}
It's a basic little question but i don't know how to do it.THANKS!
Either move the code in changepassword to the page your form is in, so that you can send the form to its own page and therefore no redirection needed, or you'll have to use AJAX.
I cant seem to find the problem coz my code works in localhost xampp. but once i upload to the actual server it doesn't work.
there's no errors outputted whatsoever
when i submit the form it outputs the loader and then disappears and no success message or error message outputted at <div id="status"></div>
javascript:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("bankbtn").disabled = true;
_("status").innerHTML = '<div class="progress"><div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"><span class="sr-only">Loading...</span></div></div><br />';
var formdata = new FormData();
formdata.append( "bcountry", _("bcountry").value );
formdata.append( "bname", _("bname").value );
formdata.append( "baname", _("baname").value );
formdata.append( "bno", _("bno").value );
formdata.append( "bswift", _("bswift").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "editbank_engine.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("editbank").innerHTML = '<div class="alert alert-success"><h2>Changes has been saved</h2></div>';
} else {
_("status").innerHTML = ajax.responseText;
_("bankbtn").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
html
<div class="modal fade" id="edit" tabindex="-1" role="dialog">
<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">Edit</h4>
</div>
<div class="modal-body">
<form id="editbank" onsubmit="submitForm(); return false;">
<div id="status"></div>
<input class="form-control" type="text" value="<?php echo $bank['bank_country']?>" id="bcountry" placeholder="Bank Country" required=""/><br />
<input class="form-control" type="text" value="<?php echo $bank['bank_name']?>" id="bname" placeholder="Bank Name" required=""/><br />
<input class="form-control" type="text" value="<?php echo $bank['bank_accountname']?>" id="baname" placeholder="Bank Account Name" required=""/><br />
<input class="form-control" type="text" value="<?php echo $bank['bank_no']?>" id="bno" placeholder="Bank Account No." required=""/><br />
<input class="form-control" type="text" value="<?php echo $bank['bank_swiftcode']?>" id="bswift" placeholder="Bank Swift Code"/><br />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="bankbtn" type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
php
<?php
session_start();
include_once('../php/config.php');
include_once('../php/func.php');
if(
isset($_SESSION['hotel_id']) &&
isset($_POST['bcountry']) &&
isset($_POST['bname']) &&
isset($_POST['baname']) &&
isset($_POST['bno']) &&
isset($_POST['bswift']) &&
!empty($_SESSION['hotel_id']) &&
!empty($_POST['bcountry']) &&
!empty($_POST['bname']) &&
!empty($_POST['baname']) &&
!empty($_POST['bno']) &&
!empty($_POST['bswift'])
){
$update = $dbo->prepare('UPDATE bank_details SET bank_country=:bankcountry, bank_name=:bankname, bank_accountname=:bankaccountname, bank_no=:bankno, bank_swiftcode=:bankswift, active=0, last_updated=NOW() WHERE hid=:hid AND active = 1');
$update->bindParam(':bankcountry', $_POST['bcountry'], PDO::PARAM_STR);
$update->bindParam(':bankname', $_POST['bname'], PDO::PARAM_STR);
$update->bindParam(':bankaccountname', $_POST['baname'], PDO::PARAM_STR);
$update->bindParam(':bankno', $_POST['bno'], PDO::PARAM_STR);
$update->bindParam(':bankswift', $_POST['bswift'], PDO::PARAM_STR);
//$update->bindParam(':active', '0', PDO::PARAM_STR);
$update->bindParam(':hid', $_SESSION['hotel_id'], PDO::PARAM_STR);
$update->execute();
if($update->rowCount() == 1){
echo 'success';
//echo '<div class="alert alert-success"><b>Changes has been saved</b></div>' ;
//mail_log('-User '.$_SESSION['extranet_user'].' has updated his bank details at '.date(time(), 'Y/m/d H:i:s').'');
}else{
echo '<div class="alert alert_danger"><strong>Error has occurred, You can only update once your account has been approved</strong></div>';
//mail_log(' User '.$_SESSION['extranet_user'].' has run into an error via bank details at '.date(time(), 'Y/m/d H:i:s').'');
}
}
?>
So i found the problem. its in my phpmyadmin (actual server)
i was testing my form using a test user that has a id of 0, all i had to do is change it to 1, for some reason it cannot be set as 0, or else it wont work
I am trying to code a website using Bootstrap. I already have it implemented on one page using a modal (here) and the other page doesn't seem to show the modal (here) on that page, there is a button that can edit the ban details but when I click the edit button, it does nothing.
Also, I am using jQuery for form submissions so that I can redirect to the returned ID, however, I am stuck on how my function can return the ID because using
get_mysql()->fetch_assoc($result)["id"]
causes a 500 internal server error.
Codes can be found below.
ban.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<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">Edit Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<input type="hidden" id="id" name="id" value="<?php echo $ban["id"] ?>" />
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("add.php", { id: id, uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "ban.php?id=<?php echo data ?>";
});
});
});
</script>
index.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<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">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("functions/add.php", { uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "functions/ban.php?id=<?php echo data ?>";
});
});
});
</script>
api.php
<?php
define("key", "redacted");
function get_mysql() {
$mysql = new mysqli("localhost", "redacted", "redacted", "redacted");
if($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = gmdate("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
$result = get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'");
get_mysql()->fetch_array($result);
return $result["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->num_rows > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into `users` (`username`, `password`) values ('$username', '$password'");
}
function get_key() {
return key;
}
?>
I've found the answer thanks to #stain88. I didn't provide the correct link to bootstrap.min.js (facepalm)
Thanks again #stain88.