Ajax Form Error submitting an image - php

I'm having a difficult time trying to make AJAX edit changes when the form is submitted on the same page and make the changes appear, but the image throws error: Undefined index: image in update.php on line 22 and 24. It refuses to pass the values.
Form (editForm.php):
<div class="modal-content editDisplay">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModalLabel">Edit Item</h4>
</div>
<form class="editForm" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" name="Product_Name" placeholder="Name" value="<?php echo $product ?>">
<input type="hidden" name="oldProduct" value="<?php echo $oldProduct ?>">
</div>
<div class="form-group">
<label for="inputDescription">Description</label>
<textarea class="form-control" id="inputDescription" name="Description" placeholder="Description"><?php echo $description ?></textarea>
</div>
<div class="form-group">
<label for="inputPrice">Price</label>
<input type="text" class="form-control" id="inputPrice" name="Price" placeholder="Price" value="<?php echo $price ?>">
</div>
<div class="form-group">
<label for="inputQuantity">Quantity</label>
<input type="number" class="form-control" id="inputQuantity" name="Quantity" placeholder="Quantity" value="<?php echo $quantity ?>">
</div>
<div class="form-group">
<label for="inputSalePrice">Sale Price</label>
<input type="text" class="form-control" id="inputSalePrice" name="Sale_Price" placeholder="Sale Price" value="<?php echo $salePrice ?>">
</div>
<div class="form-group">
<label for="inputImage">Image Upload</label><br>
<fieldset class="file-fieldset">
<span class="btn btn-default btn-file">
<span class="glyphicon glyphicon-upload"></span> Browse Browse <input name="image" type="file" id="inputImage"/><br>
</span>
<input type="hidden" name="prevPicture" value="<?php $image ?>"/>
<span style="margin-left:8px;" value=""><?php echo $image ?></span>
</fieldset>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary" id="saveButton" name="update">Save Changes</button>
</div>
</form>
</div>
PHP (update.php):
<?php
include('connection.php');
include('LIB_project1.php');
$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];
//$productName = 'Jaime';
//$productDescription = 'This is crazy';
//$price = '0';
//$quantity = '12234';
//$salePrice = '0';
//$oldImage = $_POST['prevPicture'];
//$oldProduct = $_POST['oldProduct'];
$imageName= $_FILES['image']['name']; //TODO line 22
echo ' The image is '.$imageName;
$image_temp = $_FILES['image']['tmp_name']; // line 24
echo 'Product name is: '.$productName;
//$productName = 'Dodo Square';
//$productDescription = 'Flower on a Bee. Such Beauty!';
//$price = 9;
//$quantity = 8;
//$salePrice = 230;
//$newImage = '038.jpg';
//$oldProduct = 'Times Square';
//working under the assumption that the image already exist in the database
$targetDirectory = 'productImages';
$files = scandir($targetDirectory,1);
//code passed
for($i=0; $i<sizeof($files); $i++)
{
if($oldImage==$files[$i])
{
unlink('productImages/'.$oldImage);
}
}
$target = "productImages";
//add the image to the directory
$target = $target.'/'.$imageName;
move_uploaded_file($image_temp,$target);
updateProduct($conn,'product',':productName', ':productDescription', ':price', ':quantity', ':imageName', ':salePrice', 'Product_Name', 'Description', 'Price', 'Quantity', 'Image_Name', 'Sale_Price', $productName, $productDescription, $price, $quantity,$imageName, $salePrice, $oldProduct, ':oldProduct');
//header('location:admin.php');
?>
updateProduct(...)
/*
* This is a function to update Product
*
*/
function updateProduct(PDO $connection,$table,$bindProductName, $bindProductDescription, $bindPrice, $bindQuantity, $bindImageName, $bindSalePrice,$productNameColumn, $productDescriptionColumn, $priceColumn, $quantityColumn, $imageNameColumn, $salePriceColumn, $productName, $productDescription, $price, $quantity, $imageName, $salePrice, $oldProduct, $bindOldProduct)
{
$result = false;
$sql = 'UPDATE ' . $table . ' SET ' . $productNameColumn . ' = ' . $bindProductName . ',' . $productDescriptionColumn . ' = ' . $bindProductDescription . ',' . $priceColumn . ' = ' . $bindPrice . ',' . $quantityColumn . ' = ' .
$bindQuantity . ',' . $salePriceColumn . ' = ' . $bindSalePrice . ',' . $imageNameColumn . ' = ' . $bindImageName . ' WHERE ' . $productNameColumn . ' = ' . $bindOldProduct;
$smtp = $connection->prepare($sql);
$smtp -> bindParam($bindProductName, $productName);
$smtp -> bindParam($bindProductDescription, $productDescription);
$smtp -> bindParam($bindPrice, $price);
$smtp -> bindParam($bindQuantity, $quantity);
$smtp -> bindParam($bindImageName, $imageName);
$smtp -> bindParam($bindSalePrice, $salePrice);
$smtp -> bindParam($bindOldProduct, $oldProduct);
if($smtp->execute() )
{
$result = true;
}
return $result;
}
AJAX (display edited changes) Problem: Need to submit those edited changes
$(document).ready(function()
{
//the user click save edit
$(".edit").on("submit",function(e)
{
e.preventDefault();
$.ajax({
type:"POST",
url:'update.php', //I will put project id here as well
data:$(".editForm").serialize(),
success:function(smsg)
{
alert(smsg);
//update the number of items the user has in their shopping cart
$.get('admin.php',function(data){
$('#refresh').load("admin.php #refresh");
//alert('success');
});
}
});
});
});

var inputImage = $("#inputImage");
var fd = new FormData(document.getElementById("editform"));
fd.append("image", inputImage);
$.ajax({
url: "",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
}
});
By default the image is not being added to the form during your post, you need to get the entire form and append the image to it before sending it. I did this for asp.net, it should work for php too though.

Add a series of tests to your PHP and you'll figure it out quite quickly yourself.
You are already alerting the response sent by the PHP ajax processor file:
alert(smsg);
So, use that to troubleshoot/diagnose where things are going wrong.
First test can be to put a "I got here" message at the top of the PHP file -- at least then you know the ajax itself is working. So, modify the top of update.php to read:
<?php
echo "Got to here";
die();
If that alerts, then get rid of the die() and echo out a few more such tests at various places in the file. Use this method to narrow down the location (in the PHP file) of the error.
Echo out the data received so you know what is coming in. Modify update.php to be:
$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];
echo "$productName: " .$productName. " -- $productDescription: " .$productDescription. " - etc etc etc";
die();
I'm sure you'll find the error pretty quick -- certainly quicker than composing a detailed SO question and awaiting the answer...
Good luck!

Maybe it's because the image never send to server via ajax, so $_FILES have nothing under 'image' index.
Take a look at how to do file upload using jquery serialization
or consider to use FormData object.

Change <input name="image" type="file" id="inputImage"/ to <input name="image" type="file" id="inputImage"/>

Related

Set column as empty if no file is selected when submit

I am very new to PHP and was trying to do the file uploading. When I try to submit a form without having any files selected, the database will still insert a value to the attachments column.
My table picture:
Is there any way that I can set the attachments column as empty if there is not file selected for submission. Below is my code:
view_group.php
<form class="forms-sample" enctype='multipart/form-data' method="post">
<div class="modal-body">
<div class="form-group">
<textarea id="status_content" name="status_content" rows="30"></textarea>
</div>
<div class="form-group">
<label for="section_label">Add Attachments</label><br>
<input type="text" class="form-control" id="file" disabled placeholder="Select a file"><br>
<button type="button" class="file-upload-browse btn btn-primary" name="button" onclick="document.getElementById('fileName').click()">Select a file</button>
<input type="file" name="attachmentfile" id="fileName" style="display:none">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary btn-fw">Cancel</button>
<input type="submit" class="btn btn-primary" name="postStatus" value="Post" />
</div>
</form>
GroupsController.php
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}
GroupsModel.php
function postStatus() {
$sql = "insert into status(std_id, group_id, status_content, attachments) values(:std_id, :group_id, :status_content, :attachments)";
$args = [':std_id'=> $this->std_id, ':group_id'=> $this->group_id, ':status_content'=> $this->status_content, 'attachments'=> $this->attachments];
move_uploaded_file($_FILES['attachmentfile']['tmp_name'],$this->target_dir.$this->attachments); $stmt = DB::run($sql, $args);
$count = $stmt->rowCount(); return $count; }
I'm sorry if the question sounded dumb. It would be really great if someone can help. Thank you!
UPDATE!
Thanks to the people in my comment section, I finally get to do it. Here are the code needed to add :
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($_FILES['attachmentfile']['name']) {
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
} else {
$status->attachments = '';
}
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}

How to pass an id of current item to request table

I have an application where a user can send request edit to the admin, now the problem is how to store the id of the requested asset from user_asset table to the request table so I can display it to the admin's page with full details of the asset
when the user clicks on the request edit he gets a form with editable fields filled with current information but how can I store this asset's id so I can fetch it to the admin's table with information from both tables (user_assets, requests)
I have user_asset table
asset_id
asset_category
code
title
userid
and requests table
id
reason
assetid
user_id
this is what I have done so far
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
?>
and this is my form
<form method="post" action="req_ade.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
these are the errors I'm getting
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Incorrect integer value: '' for column 'assetid' at row 1' in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
( ! ) mysqli_sql_exception: Incorrect integer value: '' for column 'assetid' at row 1 in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
There is no "id" in your $_GET array. So your $asset_id variable will be empty and a empty string is not a valid int number. You should add (int) in your query:
mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". (int)$asset_id ."','" .$_SESSION['user_id'] . "')")
Or better check the the $_GET array before you use it. Like this:
If(isset($_GET['id']))
{
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
}
else
{
...
}
Thank you for all your suggestions.
After trying a lot of suggestions and manipulating with the code I have found a solution for it.
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_POST['asset_id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests1`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
and this is the form I have posted the asset_id in a hidden type
<form method="post" action="req_ade1.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="hidden" value="<?php echo $project['asset_id'];?>" name="asset_id" />
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>

form not adding input data into db table

Im working on a Opencart project and Im having trouble getting input data into db table. Currently when i submit it enters an empty record into the db.
I have a form that has several inputs and a save button. The query from the model works just fine when entered in phpmyadmin so Im having issues between the view and controller. This is a large pr0ject is overly confusing to me. Any help would be appreciated
html:
" class="btn btn-primary">
<form method="post" enctype="multipart/form-data" id="form-campaign" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5 col-sm-push-1 form-group required>
<label class="col-sm-2 control-label" for="input-campaign-name"><?php echo $entry_name; ?></label>
<input type="text" name="name" value="" placeholder="<?php echo $entry_name; ?>" id="input-campaign-name" class="form-control" />
<?php if (isset($error_name[$language['language_id']])) { ?>
<div class="text-danger"><?php echo $error_name[$language['language_id']]; ?></div>
<?php } ?>
</div>
</div>
<div class="col-sm-5 col-sm-push-1 form-group required>
<label class="col-sm-2 control-label" for="input-campaign-goal"><?php echo $entry_goal; ?></label>
<input type="text" name="goal" value="" placeholder="<?php echo $entry_goal; ?>" id="input-campaign-goal" class="form-control" />
<?php if (isset($error_name[$language['language_id']])) { ?>
<div class="text-danger"><?php echo $error_name[$language['language_id']]; ?></div>
<?php } ?>
</div>
</div>
</form>
php: controller
public function add() {
$this->load->language('campaigns/campaign');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('campaigns/campaign');
if (($this->request->server['REQUEST_METHOD'] == 'POST')) {
$this->model_campaigns_campaign->addCampaign($this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$url = '';
if (isset($this->request->get['filter_campaign_id'])) {
$url .= '&filter_campaign_id=' . $this->request->get['filter_campaign_id'];
}
if (isset($this->request->get['filter_campaign_name'])) {
$url .= '&filter_campaign_name=' . urlencode(html_entity_decode($this->request->get['filter_campaign_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_campaign_goal'])) {
$url .= '&filter_campaign_goal=' . $this->request->get['filter_campaign_goal'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$this->response->redirect($this->url->link('campaigns/campaign', 'token=' . $this->session->data['token'] . $url, true));
}
$this->getForm();
}
php: model
public function addCampaign() {
$this->db->query("INSERT INTO " . DB_PREFIX . "campaigns SET campaign_name = '" . $this->db->escape($data['campaign_name']) . "', campaign_giving_goal = '" . (float)$data['campaign_giving_goal']
. "', campaign_giving_count_goal = '" . (float)$data['campaign_giving_count_goal'] . "', campaign_owner = '" . $this->db->escape($data['campaign_owner']). "'");
$this->cache->delete('campaign');
return $campaign_id;
}

PHP Form update without logout

As i am newbie to PHP kindly pardon me if i looks silly ,
I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes .
Whereas if i logout and login again , the form shows the updated value .
I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login .
Kindly help me on viewing the changes while i am still inside the login .
My code is as follows :
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($link);
}else {
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php $_PHP_SELF ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php
}
?>
SOLUTION
1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value
2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value )
3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this:
<?php
$name = '';
$email = '';
$password = '';
$update_id = '';
//$img = '';
//$role = '';
//$link = null;
if(
isset($_POST['update']) &&
isset($_POST['id']) &&
isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['password'])
) {
$update_id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if(!$result)
die('Could not update data: ' . mysql_error($link));
echo 'Updated data successfully', "\n";
}
elseif(isset($_GET['id'][0])) {
$update_id = mysql_real_escape_string($_GET['id']);
$sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if($result) {
$result = mysql_fetch_row($result);
$name = $result[0];
$email = $result[1];
$password = $result[2];
}
else {
echo 'Could not find the id.' . "\n";
$update_id = '';
}
}
unset($result);
if(isset($update_id[0])) {
mysql_close($link);
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image">
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3>
<h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5>
</div>
<div class="box-footer no-padding">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php }
else {
$sql = 'SELECT aid,a_name FROM admin';
$result = #mysql_query($sql, $link);
if($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '' . $row['a_name'] . '<br />' . "\n";
}
}
mysql_close($link);
}
?>
As #DivyeshSavaliya mentioned in the comment the issue is ,
I didn't Used Select query after update . Once done that the issue solved
The new working code is
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
Thanks to #DivyeshSavaliya

Edit PHP/AJAX to deal with DELETE OR EDIT

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.

Categories