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'];
}
}
Related
Need some help doing my update Ajax call. What I want my code to do is to show when on click my update form and pass the data from the form to my update via AJAX. So far the form isn't showing on click nor is the update working. Everything else seems to be working right except for that.
index.php
<?php include 'includes/header.php' ?>
<div class="main" id="maincontent">
<div class="main-section">
<div class="add-section">
<form action="app/add.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> + </button>
<?php }else{ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<button type="submit" aria-label="Enter"> + </button>
<?php } ?>
</form>
</div>
<?php
$todos = $conn->query("SELECT * FROM todos ORDER BY id DESC");
?>
<div class="show-todo-section">
<?php if($todos->rowCount() <= 0){?>
<div class="todo-item">
<div class="empty">
<p>Enter a To Do!</p>
<img src="img/f.jpg" alt="Notebook" width="100%" height="175px" />
</div>
</div>
<?php } ?>
<?php while($todo = $todos->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="todo-item">
<span id="<?php echo $todo['id']; ?>" class="remove-to-do" aria-label="Delete"><i class="fa fa-trash" style="font-size:18px"></i></span>
<span id="<?php echo $todo['id']; ?>" class="update-to-do" aria-label="Edit">
<i class="fa fa-pencil" style="font-size:18px"></i></span>
<?php if($todo['checked']) { ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box" checked />
<h2 class="checked"><?php echo $todo['title'] ?></h2>
<?php }else{ ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box">
<h2><?php echo $todo['title'] ?></h2>
<?php } ?>
<br>
<small>Created: <?php echo $todo['date_time'] ?> </small>
<div style="display:none;" class="update"><?php include 'updateForm.php'?></div>
<!---->
</div>
<?php } ?>
jQuery
<script>
$(document).ready(function(){
$('.remove-to-do').click(function(){
const id = $(this).attr('id');
$.post("app/remove.php",
{
id: id
},
(data) =>{
if(data){
$(this).parent().hide(600);
}
}
);
});
$(".check-box").click(function(e){
const id = $(this).attr('data-todo-id');
$.post("app/check.php",
{
id: id
},
(data) =>{
if(data != 'error')
{
const h2 = $(this).next();
if(data === '1'){
h2.removeClass('checked');
}else{
h2.addClass('checked');
}
}
}
);
}); /* */
$(".update-to-do").click(function(e){
const id = $(this).attr('id');
var title = $(this).attr('id'); //find
var month = $(this).attr('id');
var year = $(this).attr('id');
$.post("app/update.php",
{
id: id,
title: title,
month: month,
year : year
},
(data) =>{
//alert(id);
if(data != 'error')
{
var x = document.getElementsByClassName(".update");
if(form.hide()){
form.show();
}else{
form.hide();
}
}
}
);
});
});
updateForm.php
<div class="add-section">
<form action="app/update.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="id" style="display:none;"></label>
<input type="hidden" id= "id" name="id" value="<?php echo $_GET['id']; ?>" aria-label=""/>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> + </button>
<?php }else{ ?>
<label for="id" style="display:none;"></label>
<!--<input type="hidden" id= "id" name="id" value="<?php //echo $_GET['id']; ?>" aria-label="id"/> -->
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<div class="pad"></div>
<button type="submit" aria-label="Enter"> + </button>
<?php } ?>
</form>
</div>
update.php
<?php
if(isset($_POST['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
$title = $_POST['titleUp'];
$month = $_POST['monthUp'];
$year = $_POST['yearUp'];
$dateMonth;
$futureDate;
if(empty($id))
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
else
{
if( (!empty($title)) && (empty($month)) && (empty($year)) )
{ //need to filter 0 so its registered as not empty
$title = validTitle($title);
$stmt = $conn->prepare("UPDATE todos(title) VALUE(?) WHERE id=?");
$res = $stmt->execute([$title, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (empty($year)) )
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = date("Y");
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (!(empty($year))))
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = validYear($year);
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
}
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
?>
You are POSTing to the page but checking for GET.
Good manual pages to read:
Handling external variables
Example:
$.post("app/update.php",
{
id: id
alert(id);
},
That will send a POST to the app/update.php script you have which contains the following:
<?php
// $GET is not the same as $_GET
if(isset($GET['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $GET['id'];
echo $id;
This will not work given that you are POSTing but looking incorrectly at $GET (which should be $_GET).
To fix change the following lines to:
<?php
if($_POST['id']){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
Please note that $GET and $_GET aren't the same things, nor are $POST and $_POST.
I'm trying to update the variable description with the value of the textarea.
Here is my html:
<form action="index.php" method="post">
<div class="search">
<label for="animalId">Search for Id</label><br>
<input type="text" name="animalId" value="<?php echo $animalId; ?>">
</div>
<div class="animal_description">
<label for="animalDescription">Animal's description:</label><br>
<textarea name="animalDescription" id="animal-Description" cols="30" rows="10"><?php echo
$animalDescription; ?></textarea>
</div>
<button type="submit" name="Update">Update</button>
</form>
Here is my php code to update the description variable:
//if the update button is clicked
if (isset($_POST['update'])) {
//getting variable
$animalId = $_POST['animalId'];
$animalDescription = $_POST['animalDescription'];
//checking if any empty field
if(empty($animalId)){
$ERRORS['animal-description'] = "The id field is requiered";
}
else {
$idQuery = "UPDATE animals SET description='$animalDesription' WHERE id_num='$id'";
$stmt = $conn->prepare($idQuery);
if ($stmt->execute()) {
$ERRORS['final-message'] = "Successfully updated the database";
}
else {
$ERRORS['final-message'] = "Failed to connect";
}
}
}
When I enter an existent Id and some text in the textarea, it does nothing just refresh the page.
Try:
<form action="index.php" method="post">
<div class="search">
<label for="animalId">Search for Id</label><br>
<input type="text" name="animalId" id = "animalId" value="<?php echo
$animalId; ?>">
</div>
<div class="animal_description">
<label for="animalDescription">Animal's description:</label><br>
<textarea name="animalDescription" id="animalDescription" cols="30"
rows="10"><?php echo
$animalDescription; ?></textarea>
</div>
<button type="submit" name="Update">Update</button>
</form>
//if the update button is clicked
if (isset($_POST['Update'])) {
//getting variable
$animalId = $_POST['animalId'];
$animalDescription = $_POST['animalDescription'];
//checking if any empty field
if(empty($animalId)){
$ERRORS['animal-description'] = "The id field is requiered";
} else {
$idQuery = "UPDATE animals SET description=? WHERE
id_num=?";
$stmt = $conn->prepare($idQuery);
$stmt->bind_param("si", $animalDescription, $animalId);
if ($stmt->execute()) {
$ERRORS['final-message'] = "Successfully updated the database";
}
else {
$ERRORS['final-message'] = "Failed to connect";
}
}
}
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.
I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>
First of all before i show you the code i will explain how my webpage works.
User selects date -> AJAX Calls On Date Change
Resulting PHP data displays in two sections on page.
First Section is Orders Table Contents
Second Section is Items Table Contents (not including the items inside Orders)
What i am trying to add is functionality to 3 buttons that will change the tables dynamically using AJAX.
I currently have working non ajax requests.
Here is the Code:
$(document).ready(function(){
$('.date-picker').change(function(){
$.ajax({
type: 'POST',
url: 'php/getproduct.php',
data: {dateorderpicker: $('.date-picker').val()},
dataType: 'JSON',
success: function(data)
{
$("#cartrow").html(data.result_1);
$("#otheritems").html(data.result_2);
}
});
});
});
PHP file for Current AJAX:
session_start();
include('db_config.php');
$datepicker = $_POST['dateorderpicker'];
$sql = "SELECT * FROM orders WHERE deliveryDate = ? AND customerId = ? ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $datepicker, PDO::PARAM_STR);
$stmt->bindParam(2, $_SESSION['customer_id'], PDO::PARAM_INT);
$stmt->execute();
$container = array();
$data['result_1'] = $data['result_2'] = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$container[] = "'{$row['itemName']}'"; // put them inside a temporary container
$data['result_1'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/edit.php" method="post" class="form-inline pull-right">
<h3>' . $row['itemName'] . '</h3>
<h4>Total Price: $'.$row['price'].'</h4>
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>Our best seller. Full of flavour.</p>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" value="' . $row['qty'] . '">
</div>
</div>
<input type="hidden" name="id" value="'.$row['id'].'">
<button type="submit" name="update" class="btn btn-primary">Update</button>
<button type="submit" name="delete" class="btn btn-primary">Remove</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
if(!empty($container)){
$excluded_names = implode(',', $container);
$sql = "SELECT * FROM item WHERE itemName NOT IN($excluded_names)";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input id="itemname" type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input id="price" type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input id="description" type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input id="qty" type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
else
{
$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
echo json_encode($data);
exit;
Both Update and Delete PHP file:
include('db_config.php');
if (isset($_POST['update']))
{
$qty = $_POST['qty'];
$id = $_POST['id'];
echo $id;
$sql = "UPDATE orders SET qty=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($qty,$id));
header('Location: ../order.php');
}
if (isset($_POST['delete']))
{
$id = $_POST['id'];
$sql = "DELETE FROM orders WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
header('Location: ../order.php');
}
The code above needs to be converted to AJAX, and both sections on the page using ajax should update the table automatically. It might be that you will call the first ajax query to reload the tables correctly?
Thanks for having a look at this.
I am having trouble wrapping my head around how i should get this work.
Alex
It is easy you can give a class (NOTE : yes class ) to your update button and similarly to delete button
Suppose your update button has class "update_task"
but your content was added to DOM after DOM already loaded, so you will need to create two ajax request with DELEGATE Methods for delete and update.
For delegate reference -
http://api.jquery.com/delegate/
// for update
$("body").delegate(".update_task","click",function(){
current_id = $(this).previous("input:hidden").val() // for current update button id,
$.ajax({
type: 'POST',
url: 'php/update_product.php',
data: {id: current_id, othervalues: other_value_of_choice},
dataType: 'JSON',
success: function(data)
{
if(data==1)
{
// what ever you want to do if data has been updated
}
}
});
});
Send AJAX request to PHP for update/delete. Return result of operation (true/false).
If result is true, update/remove from html with javascript(jquery).
By the way, don't use redirect, when you call php via ajax.