Ajax live insertion double submit glitch - php

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.

Related

What is the best way to write an insert code with PDO?

I have recently learned Object Oriented Programming PHP, and I tried to test my knowledge on that, so I tried to write some queries by myself...
(Example practice: inserting new row, updating a row and deleting a row).
And here is of the templates that I've coded myself in order to Insert New Row into database:
class Register
{
protected $notice = array();
private $_db;
public function __construct()
{
$this->_db = new Connection();
$this->_db = $this->_db->dbConnect();
}
public function CheckUname($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$chk1 = $this->_db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $this->notice;
}else{
$chk2 = $this->_db->prepare("SELECT email_address FROM admins WHERE email_address = ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
return $this->notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $this->notice;
}
}
}
}
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->_db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups);
$reg->bindParam(5,$level);
$reg->execute();
}
}
public function getNotice()
{
return $this->notice;
}
}
And I called this Class on index:
<?php
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Administrator"){
$level = 2;
}else if($groups == "ContentCreatorBlog"){
$level = 3;
}else if($groups == "ContentCreatorShop"){
$level = 4;
}else if($groups == "ContentCreatorGallery"){
$level = 5;
}else if($groups == "Secretary"){
$level = 6;
}else if($groups == "SocialMediaManager"){
$level = 7;
}else if($groups == "Analyst"){
$level = 8;
}else{
$level = Null;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email_validation'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
}
}
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Add New Admin
<small>You can add new admin here</small>
</h1>
<ol class="breadcrumb">
<li class="active">addnewadmin.php</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-primary" id="myModal1">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<?php
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<form role="form" method="POST" action="" data-tour-index="1" data-tour-title="Card Type" data-tour-description="A card will usually be one of multiple similar type items on a page.">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control" name="groups">
<option value="Administrator">Administrator</option>
<option value="ContentCreatorBlog">Blog Content Creator</option>
<option value="ContentCreatorShop">Shop Content Creator</option>
<option value="ContentCreatorGallery">Gallery Content Creator</option>
<option value="Secretary">Secretary</option>
<option value="SocialMediaManager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin new documentation to know more about this page.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
So shortly what it does is showing the form and take some information and assign to parameters and then call the Class:
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
So if the form faced any error such as:
already registerd username error
already exists email address error
It should simply take back an error message and show it to users by these code on the index page:
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
Question:
The problem with this code is that the error messages does not pop up when a user enters information despite of the rules. However it still adds new row to table correctly.
So now the question is "Why the errors does not show up on page when users enters wrong information? Which part I made a mistake"
There's an diffrence between $notice and $this->notice. $notice is a local var and $this->notice is a class var. In your case, you only create a local var, assign a value, but return the still empty class var.
To fix this, simply replace it with $this->notice[..] = ....
But there are also other logical issues. Why does CheckUname creates a user? It would be the task of NewAdmin to call CheckUname. Also you could merge the two database queries into one, asking, if there's a entry with the username or the password. There's more to fix/change, but that would be part of Code Review
Your $notice variable will always be "not set" below. All the variables will be reset after post processing. However, you can redirect to the url that has the $notice variable. For instance, after all the processing you can:
redirect_to('index.php?notice=1');
where redirect_to is a function that takes a url.
function redirect_to($path){
die("<meta http-equiv='refresh' content=0;URL='".$path."' />");
}
And then in your index.php, you can check the notice variable if it is set. There are different ways on how to do this though.
EDIT:
function redirect_to($path){
header("Location: " . $path);
}

retrieve php error messages on bootstrap modal form submitting with ajax

I have a bootstrap form and i use jquery modal so i can open it on the same index.php window and when it is submitted the form should close and save data to database which it does on the other hand if there are error messages from formValidation.php file then it should show error messages instead of closing form.Now it does disappear even if there are errors and when i open it up again error messages are shown.I know there has been similar questions but i really cant make up solution for weeks from all sources i can get so i am a bit frustrated.Would appreciate help.Here is my code.
Here is my form from index.php file
<div class="container" id="register" style="display:none">
<div class="row centered-form">
<div class="col-xs-12 col-sm-8 col-md-4 col-sm-offset-2 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Banāns <small>Sia</small></h3>
</div>
<div class="panel-body">
<form role="form" class="ajax" method="post" action="index.php">
<?php include('classes/errors.php'); ?>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Vārds</label>
<input type="text" name="firstname" value="<?php echo $firstName;?>" id="firstname" class="form-control input-sm" placeholder="Vārds">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Uzvārds</label>
<input type="text" name="lastname" value="<?php echo $lastName;?>" id="lastname" class="form-control input-sm" placeholder="Uzvārds">
</div>
</div>
</div>
<div class="form-group">
<label>Lietotājvārds</label>
<input type="text" name="username" value="<?php echo $userName;?>" id="username" class="form-control input-sm" placeholder="Lietotājvārds">
</div>
<div class="form-group">
<label>E-pasts</label>
<input type="email" name="email" value="<?php echo $email;?>" id="email" class="form-control input-sm" placeholder="E-pasta adrese">
</div>
<div class="form-group">
<label>Telefona numurs</label>
<input type="number" name="number" value="<?php echo $number;?>" id="number" class="form-control input-sm" placeholder="Telefona numurs">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Parole</label>
<input type="password" name="password1" id="password1" class="form-control input-sm" placeholder="Parole">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Apstipriniet paroli</label>
<input type="password" name="password2" id="password2" class="form-control input-sm" placeholder="Apstipriniet paroli">
</div>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Register" class="btn btn-info btn-block">
<span id="success_msg"></span>
<span id="error_msg"></span>
<p>Aizvērt ...</p>
</form>
</div>
</div>
</div>
</div>
</div>
Here is my formValidation.php
<?php
include('classes/config.php');
$firstName = $lastName = $userName = $email = $number = $password1 = $password2 = "" ;
$errors = array();
if(isset($_POST["submit"])) {
$firstName = mysqli_real_escape_string($con, $_POST["firstname"]);
$lastName = mysqli_real_escape_string($con, $_POST["lastname"]);
$userName = mysqli_real_escape_string($con, $_POST["username"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$number = mysqli_real_escape_string($con, $_POST["number"]);
$password1 = mysqli_real_escape_string($con, $_POST["password1"]);
$password2 = mysqli_real_escape_string($con, $_POST["password2"]);
if (empty($firstName)) {
array_push($errors, "Lūdzu ievadiet vārdu.");
} else {
$firstName = test_input($firstName);
if (!preg_match("/^[a-zēūīāšžčķļņA-ZŅĒŪĪĀŠŽČĶĻŅ]*$/",$firstName)) {
array_push($errors, "Lūdzu ievadiet tikai burtus.");
}
}
if (empty($lastName)) {
array_push($errors, "Lūdzu ievadiet uzvārdu.");
} else {
$lastName = test_input($lastName);
if (!preg_match("/^[a-zēūīāšžčķļņA-ZŅĒŪĪĀŠŽČĶĻŅ]*$/",$lastName)) {
array_push($errors, "Lūdzu ievadiet tikai burtus.");
}
}
if (empty($userName)){
array_push($errors, "Lūdzu ievadiet lietotājvārdu.");
} else {
$userName = test_input($userName);
if(strlen($userName <= "6")){
array_push($errors, "Lietotājvārdam jāsastāv no vismaz 6 burtiem un/vai cipariem.");
}
}
if (empty($email)) {
array_push($errors,"Lūdzu ievadiet e-pasta adresi.");
} else {
$email = test_input($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "Lūdzu pārbaudiet e-pasta adresi.");
}
}
if (empty($number)) {
$number = "NULL";
} else {
$number = test_input($number);
if (!preg_match("/^[0-9]{8}$/", $number)) {
array_push($errors, "Lūdzu ievadiet 8 ciparu numuru.");
}
}
if(!empty($password1) && $password1 == $password2){
$password1 = test_input($password1);
$password2 = test_input($password2);
} elseif ($password1 != $password2){
array_push($errors, "Paroles nesakrīt.");
} else {
array_push($errors, "Lūdzu ievadiet paroli.");
}
if(count($errors) == 0){
$password = md5($password1);
$query = "INSERT INTO users(firstname, lastname, username, email, phonenumber, password)
VALUES ('$firstName', '$lastName', '$userName', '$email', '$number', '$password')";
mysqli_query($con, $query);
$_SESSION["username"] = "$userName";
$_SESSION["succes"] = "Apsveicu, tu esi pieslēdzies!";
header("location: index.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
and my error messages are looped trough in seperate errors.php file and are echoed in error class in index.php
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
And finally Ajax
This submits the form and it closes even if there are error messages.
$("#submit").click(function() {
e.preventDefault();
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var username = $("#username").val();
var email = $("#email").val();
var number = $("#number").val();
var password1 = $("#password1").val();
var password2 = $("#password2").val();
var submit = $("#submit").val();
$.ajax({
url: "classes/formValidation.php",
method: "POST",
data: {
firstname: firstname,
lastname: lastname,
username: username,
email: email,
number: number,
password1: password1,
password2: password2,
},
success: function(data){
if(data == "success"){
$("#register").hide();
location.reload();
}else{
return false;
}
}
});
});
And i have tried this
If i open up console it retrieves all my form name attributes in an object.I have tried to change action to my formValidation.php or errors.php but it does not work.
$('form.ajax').on('submit', function(){
var bzz = $(this),
url = bzz.attr('action'),
method = bzz.attr('method'),
data = {};
bzz.find('[name]').each(function(index, value) {
var bzz = $(this),
name = bzz.attr('name'),
value = bzz.val();
data[name] = value;
console.log(data);
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});

Ajax not sending FormData

I have several other identical functions working successfully but I can not get this last bit to work (The photo being 'uploaded' is not storing in the database). Any help at all would be much appreciated. I understand the mysql statements are a deprecated version and will be changed.
Ajax function
function uploadProLicense5() {
var ajax = new XMLHttpRequest();
var dataFive = new FormData();
dataFive.append("professionalLicensePhotoFifthProivder", document.querySelector("#professionalLicensePhotoFifthProivder").files[0]);
ajax.open("POST", "home.php");
ajax.onreadystatechange = function() {
if (ajax.readyState === 4) {
if (ajax.status === 200) {
// OK
$('#success_prolicense5').fadeIn().html("Photo Saved");
setTimeout(function(){
$('#success_prolicense5').fadeOut("Slow");
}, 2000);
// here you can use the result (ajax.responseText)
} else {
// not OK
alert('failed to upload photo, please try again');
}
}
};
ajax.send(dataFive);
}
Html
<div class="well col-lg-4 col-lg-offset-4 col-md-4 col-md-offset-4 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1" id="professionalphotoRow5">
<div class="text-center">
<label>Upload professional license photo:</label>
</div>
<div class="text-center">
<label id="label5thproviderPro">for 5th provider</label>
</div>
<div class="col-sm-offset-4 col-xs-offset-4">
<input name="professionalLicensePhotoFifthProivder" id="professionalLicensePhotoFifthProivder" class="filestyle" data-input="false"
type="file" accept="image/*">
</div>
<?php
$savedTxt = "Photo Saved";
$notSavedTxt = "Photo Not Saved";
if (!empty($userRow[pro_license_photo_provider_five])) {
echo "<i class='glyphicon glyphicon-ok col-sm-offset-4 col-xs-offset-4' style='color: greenyellow;'>" . "</i> " . $savedTxt;
}
?>
<br>
<div class="col-sm-offset-4 col-xs-offset-4">
<input id="saveProfessionalPhoto5" type="button" class="btn btn-default"
name="saveProfessionalPhoto5" onclick="uploadProLicense5()"
value="upload photo" style="background-color: #1d2b5c; color: white"/>
</div>
<span id="success_prolicense5" class="text-success col-sm-offset-4 col-xs-offset-4"></span>
</div>
PHP
$db_pro_license_img_provider_five = addslashes(file_get_contents($_FILES['professionalLicensePhotoFifthProivder']['tmp_name']));
$pro_image_data_provider_five = base64_encode($userRow[pro_license_photo_provider_five]);
$pro_data_provider_five = substr($pro_image_data_provider_five, strpos($pro_image_data_provider_five, ","));
if(!empty($db_pro_license_img_provider_five)){
$sql = "UPDATE `wp_form` SET
`pro_license_photo_provider_five`='$db_pro_license_img_provider_five'
WHERE id =" . $_SESSION['user'];
mysql_query($sql) or die(mysql_error());
$res = mysql_query("SELECT * FROM wp_form WHERE id=" . $_SESSION['user']);
$userRow = mysql_fetch_array($res);
}
Here's my network request
And then my empty blob : (

Inserting angularjs form values into database using php

I have created angularjs form. I want to store the form values into data base using PHP and before inserting I want to check weather the email is already exists or not. I am new to PHP. Any help would be appreciated. Thanks.
Register.html:
<div class="container col-lg-10" style="margin-top:2em; margin-left:2em;" >
<div class="panel panel-default">
<div class="panel-body" ng-app="TempleWebApp" ng-controller="RegisterCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (userForm.name.$dirty || submitted)}">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="user.name" placeholder="Your Name" ng-required="true">
<p ng-show="userForm.name.$error.required && (userForm.name.$dirty || submitted)" class="help-block">You name is required.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && (userForm.email.$dirty || submitted)}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Your Email Address" ng-required="true">
<p ng-show="userForm.email.$error.required && (userForm.email.$dirty || submitted)" class="help-block">Email is required.</p>
<p ng-show="userForm.email.$error.email && (userForm.email.$dirty || submitted)" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && (userForm.password.$dirty || submitted)}">
<label>Password</label>
<input type="Password" name="password" class="form-control" ng-model="user.passwrd" placeholder="Your Password" ng-required="true">
<p ng-show="userForm.password.$error.required && (userForm.password.$dirty || submitted)" class="help-block">Your password is required.</p>
</div>
<!-- TERMS & CONDITIONS -->
<div class="form-group" ng-class="{ 'has-error' : userForm.terms.$invalid && (userForm.terms.$dirty || submitted)}">
<label>Accept Terms & Conditions</label>
<input type="checkbox" value="" name="terms" ng-model="user.terms" ng-required="true" />
<p ng-show="userForm.terms.$error.required && (userForm.terms.$dirty || submitted)" class="help-block">Accept terms & conditions.</p>
</div>
<!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
<!--<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Register</button>-->
<button type="submit" class="btn btn-primary col-lg-offset-6">Register</button>
</form>
<pre>{{user}}
</pre>
</div>
</div>
</div>
Main.js:
var app = angular.module('TempleWebApp', [ 'ngRoute']);
app.controller('RegisterCtrl', function ($scope,$location, $http) {
$scope.user = {};
$scope.user.name= "" ;
$scope.user.email ="";
$scope.user.passwrd="";
$scope.user.terms="";
// function to submit the form after all validation has occurred
$scope.submitForm = function () {
// Set the 'submitted' flag to true
$scope.submitted = true;
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
console.log("Inserted Successfully!");
});
};
});
PHP code.
<?php
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = $data->password;
$con = mysql_connect("localhost","root","");
mysql_select_db("userregister");
$sql = "insert into user(username,email,password) values($username,'$email','$password')";
$result = mysql_query($sql);
?>
Try using mysqli in the following manner (Also note you should create the variable $dbname and assign the right dbname to it:
$data = json_decode(file_get_contents("php://input"));
$username = #$data->username;
$email = #$data->email;
$password = #$data->password;
$dbname = '';
$conn = new mysqli("localhost","root","",$dbname);
$check = "SELECT * FROM user WHERE email='$email'";
//The following rows check whether this email already exists in the DB
$results = $conn->query($check);
if($results && mysqli_num_rows($results)>0)
{
echo "email";
die;
}
//The following rows will work only if there is no such email in the DB
if($conn->connect_error)
{
echo "false";
die;
}
$sql = "INSERT INTO user VALUES values($username,'$email','$password')";
if ($conn->query($sql) === true)
{
echo "true";
}
You will also need to change your Javascript to fit the possible events:
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
if(data == 'true'){
console.log("Inserted Successfully!");
}
else if(data == 'email'){
console.log("The email already exists");
}
else{
console.log("There was an issue connecting to the DB");
}
});

Can't add data through PHP and MySQL

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.

Categories