Can't add data through PHP and MySQL - php

Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added

Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.

Related

PHP MySQL Ajax form data output

I have a code that I have been trying to run for days without success, could anyone look at it and help figure where I am going crazy?
here is report.js:
$(document).ready(function() {
$('#navReport').addClass('active');
// order date picker
$('#startDate').datepicker();
// order date picker
$('#endDate').datepicker();
$('#getReportForm')
.unbind('submit')
.bind('submit', function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var personId = $('#personId').val();
if (startDate == '' || endDate == '' || personId == '') {
if (startDate == '') {
$('#startDate')
.closest('.form-group')
.addClass('has-error');
$('#startDate').after(
'<p class="text-danger">The Start Date is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
if (endDate == '') {
$('#endDate')
.closest('.form-group')
.addClass('has-error');
$('#endDate').after(
'<p class="text-danger">The End Date is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
if (personId == '') {
$('#personId')
.closest('.form-group')
.addClass('has-error');
$('#personId').after(
'<p class="text-danger">Person Name is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'text',
success: function(response) {
var mywindow = window.open(
'',
'Child Behavior Management System',
'height=400,width=600'
);
mywindow.document.write('<html><head><title>Report</title>');
mywindow.document.write('</head><body>');
mywindow.document.write(response);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
} // /success
}); // /ajax
} // /else
console.log(personId, startDate, endDate);
return false;
});
});
Here is getReport.php:
<?php
require_once 'core.php';
if($_POST) {
$personId = $_POST['personId'];
$startDate = $_POST['startDate'];
$date = DateTime::createFromFormat('m/d/Y',$startDate);
$start_date = $date->format("Y-m-d");
$endDate = $_POST['endDate'];
$format = DateTime::createFromFormat('m/d/Y',$endDate);
$end_date = $format->format("Y-m-d");
$table = '';
$sql = "SELECT notes.note_id, notes.note_content, notes.person_id,
notes.note_date, notes.note_status, persons.persons_name
FROM notes INNER JOIN persons ON notes.person_id = persons.persons_id
WHERE notes.person_id = '$personId' AND notes.note_date
BETWEEN CAST('$start_date' AS DATE) AND CAST('$end_date' AS DATE)
AND notes.note_status = 1"
$query = $connect->query($sql);
$table = '
<table border="1" cellspacing="0" cellpadding="0" style="width:100%;">
<tr>
<th>Date</th>
<th>Note</th>
<th>Resident</th>
</tr>
<tr>';
while ($result = $query->fetch_assoc()) {
$table .= '<tr>
<td><center>'.$result['notes.note_date'].'</center></td>
<td><center>'.$result['notes.note_content'].'</center></td>
<td><center>'.$result['persons.persons_name'].'</center></td>
</tr>';
}
$table .= '
</tr>
</table>
';
echo $table;
}
?>
And here is report.php:
<?php require_once 'includes/header.php'; ?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<i class="glyphicon glyphicon-check"></i> Generate Report
</div>
<!-- /panel-heading -->
<div class="panel-body">
<form class="form-horizontal" action="php_action/getReport.php" method="post" id="getReportForm">
<div class="form-group">
<label for="personId" class="col-sm-2 control-label">Resident</label>
<div class="col-sm-10">
<select type="text" class="form-control" id="personId" placeholder="Resident" name="personId" >
<option value="">~~SELECT~~</option>
<?php
$sql = "SELECT persons_id, persons_name, persons_status FROM persons WHERE persons_status = 1";
$result = $connect->query($sql);
while($row = $result->fetch_array()) {
echo "<option value='".$row[0]."'>".$row[1]."</option>";
} // while ?>
</select>
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="startDate" class="col-sm-2 control-label">Start Date</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="startDate" name="startDate" placeholder="Start Date" />
</div>
</div>
<div class="form-group">
<label for="endDate" class="col-sm-2 control-label">End Date</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="endDate" name="endDate" placeholder="End Date" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success" id="generateReportBtn"> <i class="glyphicon glyphicon-ok-sign"></i>
Generate Report</button>
</div>
</div>
</form>
</div>
<!-- /panel-body -->
</div>
</div>
<!-- /col-dm-12 -->
</div>
<!-- /row -->
<script src="custom/js/report.js"></script>
<?php require_once 'includes/footer.php'; ?>
I would love to have expert solution to this. I have looked for solution almost the entire night but no joy. The popup is not firing when I select the preferred person, start and end dates based on the query.

PDO error 42000

i had an error when i run my code and i don't understand this error
error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE UserID = 'ahmed' SET Username = 'adasda#dmail.ck',Email = 'ahmed',FullName' at line 1 in C:\wamp64\www\eC
<?php
/*
==============================================================
= Manage Member do
= you can Add | Edit | Delete Members from here
==============================================================
*/
session_start();
$pageTitle = 'Members';
if(isset($_SESSION['Username'])){
include 'init.php';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage';
// $do= '';
//
// if(isset($_GET['do'])){
//
// $do = $_GET['do'];
// }else {
// $do = 'Manage';
// }
// start Manage do
if ($do == 'Manage') {
echo 'welcom in manage do';
//Manage page
}elseif ($do == 'Edit') { //edit page
// check If the GET Request is Numeric && Get the Integer value of it
$userid = isset($_GET['userid']) && ($_GET['userid']) ? intval($_GET['userid']) : 0;
// Select the row of user from the table
// select All data Depend on this Id
$stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1");
// extract Query
$stmt->execute(array($userid));
// Fetch the data
$row = $stmt->fetch();
// the row count
$count = $stmt->rowCount(); // to count the row in the table
if ($stmt->rowCount() > 0) {
?>
<h1 class="text-center">Edit Member</h1>
<div class="container">
<form class="form-horizontal" action="?do=Update" method="POST">
<input type="hidden" name='userid' value="<?php echo $userid ?>"/>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Username</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" value="<?php echo $row['Username'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Password</label>
<div class="col-sm-10">
<input type="hidden" name="oldpassword"/>
<input type="password" name="newpassword" class="form-control" autocomplete="new-password"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">E-mail</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" value="<?php echo$row['Email'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Full-Name</label>
<div class="col-sm-10">
<input type="text" name="full" class="form-control" value="<?php echo$row['FullName'] ?>" autocomplete="off" />
</div>
</div>
<div class="form-group form-group-lg">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="save" class="btn btn-primary btn-lg" />
</div>
</div>
</form>
</div>
<?php
}else {
echo "you are not welcom in this page ";
}
}
// update page
elseif ($do == 'Update') {
echo "<h1 class='text-center'> welcom in the update page </h1>";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
# get the variable from the form
$id = $_POST['userid'];
$user = $_POST['username'];
$email= $_POST['email'];
$name = $_POST['full'];
//echo $id . $user . $pass . $name;
$stmt = $con->prepare('UPDATE users WHERE UserID = ? SET Username = ?,Email = ?,FullName = ?,');
$stmt->execute(array($user,$email,$name,$id));
echo $stmt->rowCount() . "Record Updated";
}else {
echo "you cant brows this page directly";
}
}
include $tpl . 'footer.php';
}else {
header('location: index.php');
exit();
}
?>
ommers\first_project\admin\members.php on line 110
Your update query is incorrect, you need to use the following:
$stmt = $con->prepare('UPDATE users SET Username = ?,Email = ?,FullName = ? Where UserId =?');
And change the rest of the code accordingly.

Ajax live insertion double submit glitch

This code is a savings system. But the withdrawal is not finished yet because i've found a glitch in my code. This code works fine. It can validate properly and deposite properly. And i found the glitch after I accidentally press the enter twice. And i noticed that i inserted two records in the database before clearing the password of the cashier. I want is even the cashier pressed the enter twiced.It's just insert one record in the transaction table.
this is my SavingsAddInsert.php
<?php
include("general.php");
if(isset($_POST['Submit'])){
$Amount = $_POST['Amount'];
$Password = $_POST['Password'];
$Transaction = $_POST['Transaction'];
$SaverAccount = $_POST['AccountID'];
if(empty($Amount) && empty($Password) && $Transaction == "undefined"){
$error[] = "Please Select Transaction Type and put an Amount and Password!";
}else{
if(empty($Amount) === true || $Amount === null){
$error[] = "Amount is empty";
}else{
if(!preg_match('/^[0-9.]*$/',$Amount)){
$error[] = "i only accept numeric and decimal";
}
}
if(empty($Password) === true || $Password === null){
$error[] = "Password is empty";
}else{
$Cashier_Password = Cashier_password($_SESSION['AccountID'],$Password);
if($Cashier_Password === false){
$error[] = "Cashier Password is wrong";
}
}
if($Transaction == "undefined"){
$error[] = "Please select Category in Transaction Type ";
}else{
if($Transaction == "WITHDRAW"){
if($Amount > Check_Balance($SaverAccount)){
$error[] = "Insufficient Balance!";
}
}
}
}
if(isset($error)){
echo output_errors($error);
}
if(empty($error) || $error = 0){
if($Transaction == "DEPOSITE"){//deposite
$Balance = Check_Balance($SaverAccount);
$TotalAmount = $Balance + $Amount;
$Cashier = $_SESSION['AccountID'];
$SavingsID = Get_SavingsID($SaverAccount);
$update_savings = mysql_query("UPDATE tblsavings SET TotalSavings = '$TotalAmount' WHERE AccountID = '$SaverAccount'");
if($update_savings){
$insert_transaction = mysql_query("INSERT INTO tbltransaction
(SavingsID,Cashier,ReceiveWithdraw,RunningBalance,TransactionType,Date,Time) VALUES
('$SavingsID','$Cashier','$Amount','$TotalAmount','$Transaction',now(),now())") or die(mysql_error());
if($insert_transaction){
echo "<p><i class='fa fa-check' aria-hidden='true'></i>Transaction Complete. The Total Amount of AccountNo:'".get_AccountNo($SaverAccount)."' is ".$TotalAmount."</p>";
}
}
}
else if($Transaction == "WITHDRAW"){//withdraw
unset($Password);
}
}
}
?>
this is my SavingsAdd.php
<div class="popup-wrapper">
<div class="popup-body">
<div class="popup-head">
<p>Withdraw and Deposite</p>
</div>
<?php
if(isset($_GET['Account'])){
$Account = $_GET['Account'];
$get_info1 = mysql_query("SELECT tbluserdetail.FirstName,
tbluserdetail.MiddleName,
tbluserdetail.LastName,
tbluserdetail.Image,
tbluserdetail.ImageName,
tbluserdetail.Gender,
useraccounts.AccountNo,
useraccounts.AccountID,
useraccounts.Position
FROM useraccounts
INNER JOIN tbluserdetail
ON useraccounts.UserID=tbluserdetail.UserID
WHERE useraccounts.AccountID = '$Account'");
while($row1 = mysql_fetch_array($get_info1)){
$FirstName_p = $row1['FirstName'];
$MiddleName_p = $row1['MiddleName'];
$LastName_p = $row1['LastName'];
$AccountNo_p = $row1['AccountNo'];
$AccountID_p = $row1['AccountID'];
$Gender_p = $row1['Gender'];
$Image_p = $row1['Image'];
?>
<div class="container-fluid">
<div class="row">
<div class="p-header col-md-2 col-sm-2 col-xs-2">
<?php
if(empty($Image_p)){
if($Gender_p == "Male"){
echo '<img src="img/default-male.jpg"/>';
}else if($Gender_p == "Female"){
echo '<img src="img/default-female.jpg"/>';
}
}else{
echo '<img src="data:image/jpeg;base64,'.base64_encode( $Image_p ).'"/>';
}
?>
</div>
<div class="p-info col-md-9 col-sm-9 col-xs-9">
<div class="row">
<p><?php if(isset($_GET['Account'])){ echo $FirstName_p." ".$MiddleName_p." ".$LastName_p;} ?></p>
</div>
<div class="row">
<p>Account No: <?php if(isset($_GET['Account'])){ echo $AccountNo_p;} ?></p>
</div>
</div>
</div>
<hr/>
<div id="ajaxResult">
</div>
<hr/>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Transaction Type:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<select class="form-control" name="Transaction">
<option value="undefined">Select</option>
<option value="WITHDRAW">Withdraw</option>
<option value="DEPOSITE">Deposite</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Amount:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<input type="text" class="form-control" name="Amount" id="Amount" placeholder="0.00"/>
<input type="hidden" class="form-control" name="AccountID" id="AccountID" value="<?php if(isset($_GET['Account'])){ echo $AccountID_p;} ?>" readonly>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Cashier password:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<input type="password" class="form-control" name="Password" id="Password" placeholder="••••••••••"/>
</div>
</div>
<div class="row">
<div class="float-right col-md-12">
<input type="button" value="Cancel" name="Cancel" class="btn btn-danger"/>
<input type="submit" value="Submit" name="Submit" id="Submit" class="btn btn-success"/>
</div>
</div>
</div>
<?php }}?>
</div>
</div>
and this is my javascript inside the SavingsAdd.php
var form = document.forms.namedItem("myForm");
form.addEventListener('submit', function(ev) {
var oOutput = document.getElementById("ajaxResult"),
fn = new FormData(form);
fn.append("Submit", fn.get('Submit'));
fn.append("Amount", fn.get('Amount'));
fn.append("AccountID", fn.get('AccountID'));
fn.append("Password", fn.get('Password'));
fn.append("Transaction", fn.get('Transaction'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SavingAddInsert.php', true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
if(form){
document.getElementById('Amount').value = null;
document.getElementById('Password').value = null;
var return_data = xhr.responseText;
document.getElementById("ajaxResult").innerHTML = return_data;
}
}
}
xhr.send(fn);
ev.preventDefault();
}, false);
as you can see in the image. i try to submit by pressing double enter. and the record inserted it twice.
You reset the passwort input field only after you receive a response from the server. You need to do this directly after you send the request.
If you want to keep the data (including passwort) in case the request fails, you need to add a variable stating if a request is active (and waiting). Set this to 1 or 'active' instead of emptying the password field and reset after the request was successful. As long as a request is active, your JS must not send another request.

how update value input form class result

I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)

Bootstrap modal doesn't respond to my PHP submit form

It doesn't show any error and it doesn't respond when I click Save button. I've tried the PHP insert code in other page without bootstrap and it works I wonder why it's not working in bootstrap modal.
Here's my HTML code:
<div class="modal-content">
<div class="modal-header">
<h4>Add Topic</h4>
</div>
<div class="modal-body">
<form method="POST" action="index.php" role="form">
<div class="form-group">
<label for="cCategory">Category</label>
<input type="text" class="form-control" id="cCategory" name="category" value="<?php if (!empty($categ)) { echo $categ; } ?>">
</div>
<div class="form-group">
<label for="cTitle">Title</label>
<input type="text" class="form-control" id="cTitle" name="topicTitle" value="<?php if (!empty($topicTitle)) { echo $topicTitle; } ?>">
</div>
<div class="form-group">
<label for="cDesc">Description</label>
<textarea class="form-control custom-control" rows="3" style="resize:none" name="desc" value="<?php if (!empty($desc)) { echo $desc; } ?>"> </textarea>
</div>
<div class="form-group">
<label for="cDesc">Created By</label>
<input type="text" class="form-control" id="cDesc" name="createdby" value="<?php if (!empty($created)) { echo $created; } ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
And this my PHP code:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created)) {
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ', '$topicTitle', '$desc', '$created', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
Your button Submit is out of <form></form> tag. Kepp it inside <form></form> tag to submit the form.
And also check this line:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created))
Should be:
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby']))
You are checking variables before declaring it, use $_POST instead.
Your code should look like this:
<?php
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby'])) {
$desc1 = $_POST['desc'];
$categ1 = $_POST['category'];
$topicTitle1 = $_POST['topicTitle'];
$created1 = $_POST['createdby'];
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ1', '$topicTitle1', '$desc1', '$created1', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}

Categories