Passing javascript variable to PHP using ajax but it gives error - javascript

I am trying to pass my JavaScript variable using Ajax into my PHP script but that doesn't work it given me error that it is undefined index. both codes are in different files but both of them are accessible on the main page.
Here's my script.php
<script>
function get_child_options(){
var parentID = jQuery('#parent').val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {parentID : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
And this is my php file
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/ **/core/init.php'; //Including database path stored in init.php
$parentID = (int)$_POST['parentID'];
$childQuery = "SELECT * FROM categories WHERE parent = '$parentID' ORDER BY category";
ob_start();
?>
<option value="">Select <strong>Child</strong> Category</option>
<?php while ($child = mysqli_fetch_assoc($childQuery)): ?>
<option value="<?= $child['id']; ?>"><?= $child['category']; ?></option>
<?php endwhile; ?>
<?php
echo ob_get_clean();
?>
in script the #parent is a form id i am passing to javascript using jQuery.
because of variable is not accessible PHP is not running query.
This is my products.php the main where page where this is happening
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/Online Store/core/init.php'; //Including database path stored in init.php
include 'includes/head.php'; //Including header
include 'includes/navigation.php'; //Including Navigation bar
include 'includes/script.php';
if (isset($_GET['add'])) {
$brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
$parentQuery = $db->query("SELECT * FROM categories WHERE parent = 0 ORDER BY category");
?>
<h2 class="text-center">Add A New Product</h2><hr />
<form action="products.php?add=1" method="post" enctype="multipart/form-data">
<div class="form-group col-md-3">
<label for="title">Title*:</label>
<input type="text" class="form-control" id="title" name="title" value="<?= ((isset($_POST['title']))?sanitize($_POST['title']):''); ?>" placeholder="Add a title" />
</div>
<div class="form-group col-md-3">
<label for="brand">Brand*: </label>
<select class="form-control ">
<option value="" <?= ((isset($_POST['brand']) && $_POST['brand'] == '')?' selected':''); ?> >Select Brand</option>
<?php while($brand = mysqli_fetch_assoc($brandQuery)): ?>
<option value="<?= $brand['id']; ?>" <?= ((isset($_POST['brand']) && $_POST['brand'] == $brand['id'])?' selected':''); ?> ><?= $brand['brand'] ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*: </label>
<select class="form-control" id="parent" name="parent">
<option value="" <?= ((isset($_POST['parent']) && $_POST['parent'] == '')?' select':''); ?> >Select <strong>Parent</strong> Category</option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value="<?= $parent['id']; ?>" <?= ((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':''); ?> ><?= $parent['category']; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="child">Child Category*: </label>
<select id="child" name="child" class="form-control"></select>
<?php include $_SERVER['DOCUMENT_ROOT'].'/Online Store/admin/parsers/child_categories.php'; ?>
</div>
<div class="form-group col-md-3">
<label for="price">Price*: </label>
<input type="text" id="price" name="price" class="form-control" value="<?= ((isset($_POST['price']))?sanitize($_POST['price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label for="list_price">List Price*: </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?= ((isset($_POST['list_price']))?sanitize($_POST['list_price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label>Quantity & Sizes</label>
<button class="btn btn-default btn-info form-control" onclick="jQuery('#sizesModal').modal('toggle'); return false;">Quantity & Sizes</button>
</div>
<div class="form-group col-md-3">
<label for="sizes">Sizes & Quantity preview*: </label>
<input type="text" name="sizes" id="sizes" class="form-control" value="<?= ((isset($_POST['sizes']))?$_POST['sizes']:''); ?>" readonly/>
</div>
<div class="form-group col-md-6">
<label for="photo">Photo*: </label>
<input type="file" name="photo" id="photo" class="form-control" />
</div>
<div class="form-group col-md-6">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control" rows="6" placeholder="Description" ><?= ((isset($_POST['description']))?sanitize($_POST['description']):''); ?></textarea>
</div>
<div class="form-group pull-right">
<input type="submit" class="form-control btn btn-success" value="Add Product" />
</div>
<div class="clearfix"></div>
</form>
<?php
}else{
$sql = "SELECT * FROM products WHERE deleted = 0";
$presults = $db->query($sql);
$product = mysqli_fetch_assoc($presults);
// Featured product
if (isset($_GET['featured'])) {
$id = (int)$_GET['id'];
$featured = (int)$_GET['featured'];
$featuredSql = "UPDATE `products` SET `featured` = '$featured' WHERE `products`.`id` = '$product[id]' ";
$db->query($featuredSql);
// header('Location: products.php');
}
?>
<h2 class="text-center">Products</h2>
Add Product<div class="clearfix"></div>
<hr />
<table class="table table-bordered table-condensed table-striped">
<thead>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Category</th>
<th>Featured</th>
<th>Sold</th>
</thead>
<tbody>
<?php
while($product = mysqli_fetch_assoc($presults)):
$childID = $product['categories'];
$catSql = "SELECT * FROM categories WHERE id = '$childID'";
$result = $db->query($catSql);
$child = mysqli_fetch_assoc($result);
$parentID = $child['parent'];
$pSql = "SELECT * FROM categories WHERE id = '$parentID'";
$presult = $db->query($pSql);
$parent = mysqli_fetch_assoc($presult);
$category = $parent['category'].'~'.$child['category'];
?>
<tr>
<td>
<span class= " glyphicon glyphicon-pencil"></span>
<span class= " glyphicon glyphicon-remove-sign"></span>
</td>
<td><?= $product['title']; ?></td>
<td><?= money($product['price']) ?></td>
<td><?= $category; ?></td>
<td><a href="products.php?featured=<?= (($product['featured'] == 0)?'1':'0'); ?>&id =<?= $product['id']; ?>" class=" btn btn-sx btn-default">
<span class=" glyphicon glyphicon-<?= (($product['featured'] == 1)?'minus':'plus'); ?>"></span>
</a>&nbsp <?= (($product['featured'] == 1)?'Featured':''); ?></td>
<td>0</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php
}
include 'includes/footer.php'; //Including footer
?>
Is there any other way to do it? What I am trying to do is when user selects parent category I want child category to arrange as per parent category.

Try this:
<script>
function get_child_options(){
var parentID = $(this).val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {'parentID' : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
Getting the Value by $(this) and putting single quotes around parentID data: {'parentID' : parentID},

Related

How to pass multiple inputs into a single query?

In my app I want the user to mention how many columns he wants for the table and then enter the data for those columns and create a table with those values.
Here is what I have:
<form action="" method="post">
<label for="numOfCols">Enter Number of Fields</label>
<input name="numOfCols" type="number" id="numOfCols">
<button type="submit" class="btn btn-info" name="numOfColsSubmit" >Generate</button>
</form>
<?php if(isset($_POST["numOfCols"])): ?>
<form action="" method="post">
<label for="tbName">Enter Layout Name</label>
<input type="text" name="tbName" id="tbName" class="form-control">
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<div class="row g-4">
<div class="col-sm">
<label for="col_name<?php $colNum ?>">Name</label><br>
<input class="form-control" id="col_name<?php $colNum ?>" type="text"
name="col_name<?php $colNum ?>" >
</div>
<div class="col-sm">
<label for="col_types<?php $colNum ?>">Type</label><br>
<select name="col_types<?php $colNum ?>" class="form-control" id="col_types<?php $colNum ?>">
<option value="int">INT</option>
<option value="varchar" >VARCHAR</option>
<option value="text">TEXT</option>
</select>
</div>
<div class="col-sm">
<label for="col_length<?php $colNum ?>">Length</label><br>
<input type="text" class="form-control" name="col_length<?php $colNum ?>" id="col_length<?php $colNum ?>">
</div>
<div class="col-sm">
<br><button type="submit" class="btn btn-success" name="submitaddcol<?php $colNum ?>">Submit</button>
</div>
</div>
<?php endfor; ?>
<button type="submit" name="createtb" class="btn">Create Layout</button>
</form>
<?php endif;?>
<?php if(isset($_POST["tbName"])){
$table->createTb($_POST['tbName']);
} ?>
and the function for creating the table :
function createTb($tb){
$arr = [];
if(isset($_POST['col_name'])){
$colName = $_POST['col_name'];
}
if(isset($_POST['col_types'])){
$colTypes = $_POST['col_types'];
}
if(isset($_POST['col_length'])){
$colLength = $_POST['col_length'];
}
echo $tb;
array_push($arr , $colName , $colTypes , $colLength);
$stmt = $this->pdo->prepare("CREATE TABLE $tb ($colName $colTypes($colLength)) ");
$stmt->execute([$_POST['name'], 29]);
$stmt->execute();
$stmt = null;
}
I was thinking of getting the data from the user, pass it to an array and then use that array in my query.
The problem is I cannot get all of the user data. If the user has 2 or more columns, it will always get the last column. Any insight?
(Putting the createTb($_POST['tbName']) inside the for loop for some reason results in now showing or calling the function at all)
You can name your input-fields as an array like:
<input type="text" name="col_name[]" value="foo" />
And get it with var_dump($_POST['col_name']);
In your example you could do like this:
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<input class="form-control" id="col_name_<?=$colNum ?>" type="text" name="col_name[<?=$colNum ?>]" >
<input type="text" class="form-control" name="col_length[<?= $colNum ?>]" id="col_length_<?=$colNum ?>">
<?php endfor; ?>
And get the result:
if(isset($_POST['col_name']) && is_array($_POST['col_name'])) {
for($i = 0; $i < count($_POST['col_name']); $i++) {
var_dump($_POST['col_name'][$i]);
var_dump($_POST['col_length'][$i]);
}
}

Javascript inside PHP foreach

I made a loop using foreach, to show a list of products. Then I made a modal to edit each product. I need to get the value of product dimension and I'll make a dependent drop down between 'job drop down' and 'supply drop down'. At the moment, I can't continue it with Ajax because I got a problem at the first step to get value of dimension. In this code below I tried to get 'length' value of each product through javascript. But it returns the same value, it always is the value of the first product, even if I click on the 2nd, 3rd, 4th of product in the list.
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product</th>
<th>Supplier</th>
<th>Dimension</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
$pcs_1 = 0;
$meter_1 = 0;
foreach ($stock as $s) { ?>
<tr>
<td class="small">
<?php echo $s->cat . ' - ' . $s->prod ?>
</td>
<td class="small">
<?php echo $s->spl ?>
</td>
<td class="small">
<?php echo $s->length . ' x ' . $s->width . ' x ' . $s->height . ' x ' . $s->diameter ?>
</td>
<td>
<a type="button" data-toggle="modal" class="btn btn-small" data-target="#modal_edit<?php echo $s->id ?>"><i class="fas fa-edit"></i></a>
<!--MODAL-->
<div class="modal fade" id="modal_edit<?php echo $s->id ?>" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" method="post" action="<?php echo site_url('admin/Stock/edit/') ?>">
<div class="modal-header">
<h5 class="modal-title" id="labelModal">EDIT STOCK</h5>
</div>
<div class="modal-body">
<input type="hidden" id="length_product" class="length_product" value="<?php echo $s->length ?>" />
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<?php echo form_label('JOB') ?>
</div>
</div>
<div class="col-sm-9">
<div class="form-group">
<select name="ref" id="ref" class="form-control" required onchange="GetData()">
<option value="">-- Select Job --</option>
<?php foreach ($job as $j) : ?>
<option value="<?php echo $j->id; ?>"><?php echo $j->id ?> - <?php echo $j->cust ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<?php echo form_label('Supply') ?>
</div>
</div>
<div class="col-sm-9">
<select name="supply" id="supply" class="form-control" required>
<option value="">--Select Supply--</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-warning submitBtn">edit</button>
</div>
</form>
</div>
</div>
</div> <!-- modal -->
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
Here is the javascript :
<script type="text/javascript">
function GetData() {
var length_product = $("#length_product").val();
alert(length_product);
}
</script>
The list works well, but I don't know how to get the detail of each list on javascript (passing multiple values from 'modal inside the list' to 'Javascript').
for me it looks like that you are always getting value of
<input type="hidden" id="length_product" class="length_product" value="<?php echo $s->length ?>" />
rather than option from the select element.
Try the following:
$('#ref').on('change', function(event) {
event.preventDefault();
var length_product = $(this).val();
alert(length_product);
});
and for the PHP and HTML:
<div class="form-group">
<select name="ref" id="ref" class="form-control" required>
<option value="">-- Select Job --</option>
<?php foreach ($job as $j) { ?>
<option value="<?php echo $j["id"]; ?>"><?php echo $j["id"]; ?>-<?php echo $j["cust"]; ?></option>
<?php
}
?>
</select>
</div>
Hope this helps!

Get data attribute from an array of select box

I have an account form in which the all account are being pulled from my mysql database into a dropdown menu. The user selects the account from the dropdown menu then the account code field is automatically populated via the data-acc attribute. I have added a button to add more account.
It works at first set of input and select box, but not in the next one
sample screenshot
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$('select[name="account_name[]').change(function()
{
$('.account_num').val($('select[name="account_name[]"] option:selected').data('acc'));
});
</script>
<script>
$(document).ready(function(){
var i=1;
var chart_add = '<tr id="row_chart'+i+'"><td align="center"> <input type="text" name="account_code[]" class="form-control account_num" readonly></td><td><select class="form-control selectpicker" data-live-search="true" name="account_name[]" required> <option></option><?php $account = mysqli_query($conn,"SELECT chart_of_account.acoount_no, chart_of_account.account_title from chart_of_account inner join account_group_tbl on chart_of_account.account_group = account_group_tbl.account_name where account_group_tbl.account_type = 'Expense'");while($acc = mysqli_fetch_assoc($account)){$account_no = $acc['acoount_no'];$account_title = $acc['account_title'];?><option value="<?php echo $account_title; ?>" data-price="<?php echo $account_no; ?>"><?php echo $account_title ; ?> </option><?php } ?></select></td><td><button type="button" name="remove_chart" id="'+i+'" class="btn btn-danger remove_chart"><i class="fa fa-minus"></i></button></td></tr>';
$('#add').click(function(){
i++;
$('#dynamic_field').append(chart_add);
$('.selectpicker').selectpicker('render');
});
$(document).on('click', '.remove_chart', function(){
var button_id = $(this).attr("id");
$('#row_chart'+button_id+'').remove();
});
});
</script>
<div class="row">
<div class="col-md-12">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Report Per Office</h3>
</div>
<div class="box-body">
<div class="col-md-12">
<h4>Project Procurement Management Plan (PPMP) <hr >
</div>
<div class="col-md-1">
Office:
</div>
<div class="col-md-4">
<select class="selectpicker" data-live-search="true" name="office_from" data-width="auto" required >
<option>--Select Reponsible Office--</option>
<?php
$q = "SELECT * FROM `office_code_dept`";
$r = mysqli_query($conn,$q);
while($row = mysqli_fetch_assoc($r)){
$off_desc = $row['off_name'];
?>
<option value="<?php echo $off_desc;?>"><?php echo $off_desc; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-1">Year:</div>
<div class="col-md-4"><input type="number" min="1990" max="3000" name="tax_year" class="form-control" style="text-align: center;" value="<?php echo date('Y'); ?>"></div>
<div class="col-md-2"><input type="submit" name="search" value="Search" class="btn btn-primary btn-block">
</div>
<div class="col-md-12"><br></div>
</h4>
<table class="table table-bordered" id="dynamic_field">
<thead>
<tr>
<th width="7%" rowspan="2" style="text-align: center;">Code</th>
<th width="27%" rowspan="2" style="text-align: center;">General Description</th>
<th rowspan="2" width="5%"><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus"></i></button></th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">
<input type="text" name="account_code[]" class="form-control account_num" readonly>
</td>
<td>
<select class="form-control selectpicker" data-live-search="true" name="account_name[]" required>
<option></option>
<?php
$account = mysqli_query($conn,"SELECT chart_of_account.acoount_no, chart_of_account.account_title from chart_of_account inner join account_group_tbl on chart_of_account.account_group = account_group_tbl.account_name where account_group_tbl.account_type = 'Expense'");
while($acc = mysqli_fetch_assoc($account)){
$account_no = $acc['acoount_no'];
$account_title = $acc['account_title'];
?>
<option value="<?php echo $account_title; ?>" data-acc="<?php echo $account_no; ?>">
<?php echo $account_title ; ?>
</option>
<?php } ?>
</select>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
your .change function is not bound to the new input and select box
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$('select[name="account_name[]').change(function()
{
$('.account_num').val($('select[name="account_name[]"] option:selected').data('acc'));
});
</script>
<script>
$(document).ready(function(){
var i=1;
var chart_add = '<tr id="row_chart'+i+'"><td align="center"> <input type="text" name="account_code[]" class="form-control account_num" readonly></td><td><select class="form-control selectpicker" data-live-search="true" name="account_name[]" required> <option></option><?php $account = mysqli_query($conn,"SELECT chart_of_account.acoount_no, chart_of_account.account_title from chart_of_account inner join account_group_tbl on chart_of_account.account_group = account_group_tbl.account_name where account_group_tbl.account_type = 'Expense'");while($acc = mysqli_fetch_assoc($account)){$account_no = $acc['acoount_no'];$account_title = $acc['account_title'];?><option value="<?php echo $account_title; ?>" data-price="<?php echo $account_no; ?>"><?php echo $account_title ; ?> </option><?php } ?></select></td><td><button type="button" name="remove_chart" id="'+i+'" class="btn btn-danger remove_chart"><i class="fa fa-minus"></i></button></td></tr>';
$('#add').click(function(){
i++;
$('#dynamic_field').append(chart_add);
$('.selectpicker').selectpicker('render');
$('select[name="account_name[]').change(function()
{
$('.account_num').val($('select[name="account_name[]"] option:selected').data('acc'));
});
});
$(document).on('click', '.remove_chart', function(){
var button_id = $(this).attr("id");
$('#row_chart'+button_id+'').remove();
});
});
</script>
Something like this should work.

How to use the value of a textbox in query?

How can I use properly the value of my textbox (ORDER_ID) in my query? What happening right now is, its need to click a button first in ordermodal.php in order to get the value of it, it didn;t get the value when I click the View Order. The output should be like this, when I click the View Order its getting already the value of it. I hope you can help me with my problem, I stucked at this. Thanks!
This is my code for order.php . This is where I click the View Order.
<tr>
<td><?= $order['order_id'] ?></td>
<td><?= $order['user_id'] ?></td>
<td><?= $date ?></td>
<td><?= $time ?></td>
<td><?= $order['order_deliveryCharge'] ?></td>
<td><?= $order['order_totalAmount'] ?></td>
<td><?= $order['address'] ?></td>
<td><?= $order['coordinates'] ?></td>
<td><?= $order['driver_number'] ?></td>
<td><?= $order['order_status'] ?></td>
<td><button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal" onclick="viewOrder( '<?= $order['order_id'] ?>', '<?= $order['order_id'] ?>', '<?= $order['user_id'] ?>', '<?= $date ?>', '<?= $time ?>', '<?= $order['order_deliveryCharge'] ?>', '<?= $order['order_totalAmount'] ?>', '<?= $order['address'] ?>', '<?= $order['coordinates'] ?>', '<?= $order['driver_number'] ?>', '<?= $order['order_status'] ?>')"> View Order </button>
</td>
</tr>
<?php endwhile; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<div class="panel-footer">
</div>
</div>
</div>
<script>
function viewOrder(order_id, order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("titleModal").innerHTML = "Order Information";
document.getElementsByName("ORDER_ID")[0].setAttribute("value", order_id);
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementsByName("user_id")[0].setAttribute("value", user_id);
document.getElementsByName("order_date")[0].setAttribute("value", order_date);
document.getElementsByName("order_time")[0].setAttribute("value", order_time);
document.getElementsByName("order_deliveryCharge")[0].setAttribute("value", order_deliveryCharge);
document.getElementsByName("order_totalAmount")[0].setAttribute("value", order_totalAmount);
document.getElementsByName("address")[0].setAttribute("value", address);
document.getElementsByName("coordinates")[0].setAttribute("value", coordinates);
document.getElementsByName("drivers_number")[0].setAttribute("value", driver_number);
document.getElementsByName("order_status")[0].setAttribute("value", order_status);
document.getElementsByName("viewOrder")[0].setAttribute("name", "viewOrder");
}
</script>
This is my code for ordermodal.php .
<?php
include_once 'ordermodal2.php';
/** *ordermodal.php **/
$id = "";
$order_date = "";
$order_time = "";
$order_id = "";
$order_deliverCharge = "";
$order_status = "";
$order_totalAmount= "";
$coordinates = "";
$driver_number = "";
$address = "";
$food_name="";
$special_request="";
$quantity="";
$amount="";
$orders="";
?>
<!-- MODALS --> <!-- DETAILS -->
<div id="myModal" class="modal fade" role="dialog" style="z-index: 1400;">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="" method="post" class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><center>×</button>
<h4 class="modal-title" id="titleModal">Order Information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="order_id" class="col-sm-2 control-label">Order ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="ORDER_ID" id="ORDER_ID" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="id" class="col-sm-2 control-label">User ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="user_id" id="user_id" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_date" class="col-sm-2 control-label">Order Date</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_date" id="order_date" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_time" class="col-sm-2 control-label">Order Time</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_time" id="order_time" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_deliverCharge" class="col-sm-2 control-label">Delivery Charge</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_deliveryCharge" id="order_deliveryCharge" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_totalAmount" class="col-sm-2 control-label">Total Amount</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_totalAmount" id="order_totalAmount" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">Address</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="address" id="address" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="coordinates" class="col-sm-2 control-label">Coordinates</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="coordinates" id="coordinates" placeholder="" value="" required="required" maxlength="11" readonly>
</div>
</div>
<div class="form-group">
<label for="driver_number" class="col-sm-2 control-label">Driver Number</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="drivers_number" id="drivers_number" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_status" class="col-sm-2 control-label">Order Status</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_status" id="order_status" placeholder="" value="" required="required" readonly>
</div>
</div>
<?php
$order_id = trim(addslashes($_POST['ORDER_ID']));
$sql = "SELECT food_name, special_request, quantity, amount
FROM cart_tbl
WHERE order_id=$order_id";
$result = mysqli_query(connection2(), $sql);
?>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Food</th>
<th>Special Request</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["food_name"];?></td>
<td><?php echo $row["special_request"];?></td>
<td><?php echo $row["quantity"];?></td>
<td><?php echo $row["amount"];?></td>
</tr>
<?php
}
}
?>
</table>
</div>
<div class="modal-footer">
<button type="submit" input style="background-color:#00000;color:white;float:left" name="showfood" id="showFood" class="btn btn-primary " onclick="if(!confirm('Are you sure you want to see food order?')){return false;}" > Show Food </button>
<button type="submit" input style="background-color:#4CAF50;color:white" name="submitDelivered" id="submitDelivered" class="btn btn-primary " onclick="if(!confirm('Are you sure you want to deliver order?')){return false;}" > Delivered </button>
<button type="submit" input style="background-color:#0000FF;color:white" name="submitAccept" id="submitAccept" class="btn btn-primary" onclick="if(!confirm('Are you sure you want to accept order?')){return false;}" > Accept </button>
<button type="button" style="background-color:#FFFF00;color:black" class="btn btn-success" data-toggle="modal" data-target="#myDropdown" onclick="send('<?= $_POST['order_id'] ?>')"> Send </button>
<button type="submit" input style="background-color:#f44336;color:white" name="submitCancel" class="btn btn-danger" onclick="if(!confirm('Are you sure you want to cancel order?')){return false;}">Cancel</button>
<?php
if(isset($_POST['submitDelivered'])){
$order_id = trim(addslashes($_POST['ORDER_ID']));
$query = "UPDATE order_tbl SET `order_status`='Delivered' WHERE `order_id` = $order_id";
if (mysqli_query(connection2(), $query)) {
mysqli_query(connection2(), "COMMIT");
$_SESSION['message'] = "Order Delivered"; }
else {
$_SESSION['message'] = mysqli_error(connection2());
mysqli_query(connection2(), "ROLLBACK");
}
}
if(isset($_POST['submitAccept'])){
$order_id = trim(addslashes($_POST['ORDER_ID']));
$query = "UPDATE order_tbl SET `order_status`='Accepted' WHERE `order_id` = $order_id";
if (mysqli_query(connection2(), $query)) {
mysqli_query(connection2(), "COMMIT");
$_SESSION['message'] = "Order Accepted"; }
else {
$_SESSION['message'] = mysqli_error(connection2());
mysqli_query(connection2(), "ROLLBACK");
}
}
if(isset($_POST['submitCancel'])){
$order_id = trim(addslashes($_POST['ORDER_ID']));
$query = "UPDATE order_tbl SET `order_status`='Cancelled' WHERE `order_id` = $order_id";
if (mysqli_query(connection2(), $query)) {
mysqli_query(connection2(), "COMMIT");
$_SESSION['message'] = "Order Cancelled"; }
else {
$_SESSION['message'] = mysqli_error(connection2());
mysqli_query(connection2(), "ROLLBACK");
}
}
?>
</div>
</form>
</div>
</div>
</div>
<script>
function send(order_id) {
document.getElementById("titleModal2").innerHTML = "Choose Driver";
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementsByName("send")[0].setAttribute("name", "send");
}
</script>
It would be nice if you use jquery.
//Change your button 'View Order' with this
<button type="button" class="btn btn-success" onclick="viewOrder( '<?= $order['order_id'] ?>', '<?= $order['order_id'] ?>', '<?= $order['user_id'] ?>', '<?= $date ?>', '<?= $time ?>', '<?= $order['order_deliveryCharge'] ?>', '<?= $order['order_totalAmount'] ?>', '<?= $order['address'] ?>', '<?= $order['coordinates'] ?>', '<?= $order['driver_number'] ?>', '<?= $order['order_status'] ?>')"> View Order </button>
//place this script below this function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
function viewOrder(order_id, order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
$('#titleModal').text("Order Information")
$("#ORDER_ID").val(order_id);
$("#ORDER_ID_MODAL_2").val(order_id);
$("#user_id").val(user_id);
$("#order_date").val(order_date);
$("#order_time").val(order_time);
$("#order_deliveryCharge").val(order_deliveryCharge);
$("#order_totalAmount").val(order_totalAmount);
$("#address").val(address);
$("#coordinates").val(coordinates);
$("#drivers_number").val(driver_number);
$("#order_status").val(order_status);
$("#viewOrder").attr("name", "viewOrder");
$('#myModal').modal('show');
}

Ajax issue with input, textarea blur

Have problem with submiting information via ajax.
Have for example 20 rows. Click on row and it opens all information about services.
$('tr').click(function() {
var servicesUpdateId = $(this).attr('data');
$("#"+servicesUpdateId).css({"display":"block", 'opacity':'0'}).animate({left: '0',opacity: '1',});
// save form class for ajax submit
localStorage.setItem("formId", servicesUpdateId);
});
Here html:
<tbody>
<?php
$allServices = Services::where('user_id', $mainUser->id);
foreach($allServices as $oneServices) {
?>
<tr class="services-table-hover" data="services_<?php echo $oneServices->id; ?>">
<td> <div class="services-color"></div> <img src="/assets/images/provider_img2.png" alt=""> </td>
<td class="title-name"> <?php echo $oneServices->name; ?> </td>
<td> <?php echo $oneServices->description; ?> </td>
<td> <?php echo $oneServices->duration; ?> mins </td>
<td> <?php echo $oneServices->currency; ?> <?php echo $oneServices->price; ?> </td>
<td style="line-height: 50px;"> <i class="icon-arrow-right"></i> </td>
</tr>
<?php } ?>
Then its div with info
<?php foreach($allServices as $onesServices) { ?>
<div id="services_<?php echo $onesServices->id; ?>">
<div class="portlet light minHeigh staff-hover">
<form action="" method="post" class="services_<?php echo $onesServices->id; ?>">
<div class="portlet-title tabbable-line">
<a class="goBackOne"><i class="icon-arrow-left"></i></a><h3 style="display: inline-block;"><?php echo $lang['SERVICES_LEFT_MENU_ALL']; ?></h3>
</div>
<div class="col-sm-7">
<div class="portlet-body">
<div class="tab-content">
<div class="tab-pane active" id="portlet_tab1">
<div class="form-body input-smaller">
<div class="form-group">
<label class="col-md-3 control-label" for="form_control_1"><img class="imgs" src="/assets/images/provider_img2.png" alt=""></label>
<div class="col-md-9">
<input type="text" class="form-control" name="update_service_name" style="margin-bottom:10px; font-size: 26px; font-weight: 600;" value="<?php echo $onesServices->name; ?>">
<textarea name="update_service_description" id="" cols="30" rows="10" class="form-control" style="margin-bottom:10px;" placeholder="Description"><?php echo $onesServices->description; ?></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="form_control_1"><?php echo $lang['SERVICES_INSIDE_COST']; ?></label>
<div class="col-md-9">
<input type="text" class="form-control" name="update_service_price" value="<?php echo $onesServices->price; ?>">
</div>
</div>
<div class="clearfix"></div>
<div class="form-group">
<label class="col-md-3 control-label" for="form_control_1"><?php echo $lang['SERVICES_INSIDE_TIME']; ?></label>
<div class="col-md-9">
<input type="text" class="form-control" name="update_service_duration" value="<?php echo $onesServices->duration; ?>">
</div>
</div>
<div class="clearfix"></div>
<div class="form-group">
<?php
$servicesCat = $onesServices->service_categories_id;
$servicesCat = json_decode($servicesCat);
?>
<label class="col-md-3 control-label" for="form_control_1"><?php echo $lang['SERVICES_INSIDE_LIST']; ?></label>
<div class="col-md-9">
<select id="multiple2" name="update_services_category" class="form-control select2-multiple" multiple placeholder="Select categories">
<?php foreach($servicesCategories as $onCategory) { ?>
<?php if(in_array($onCategory->id, $servicesCat)) { ?>
<option value="<?php echo $onCategory->id; ?>" selected><?php echo $onCategory->name; ?></option>
<?php } else { ?>
<option value="<?php echo $onCategory->id; ?>"><?php echo $onCategory->name; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-5">
<h4><?php echo $lang['SERVICES_INSIDE_PROVIDE']; ?></h4>
<?php
$staffs_eupdate = Staffs::where('id_users', $mainUser->id);
$serviceStaff = ServiceStaffs::find_by_query("SELECT staff_id FROM service_staffs WHERE user_id = '$mainUser->id' AND services_id = '$onesServices->id' ");
$newStaffId = array();
foreach($serviceStaff as $index => $sStaff) {
$newStaffId[$index] = $sStaff->staff_id;
}
foreach($staffs_eupdate as $staff_update) {
?>
<div class="full-services">
<div class="all-services">
<?php if(in_array($staff_update->id, $newStaffId)) { ?>
<div class="all-around all-around-on">
<div class="float-on-left">
<div class="ignore_img"><input type="hidden" name="update_staffs_id[]" value="<?php echo $staff_update->id; ?>"></div>
<?php echo $staff_update->name; ?>
</div>
</div>
<?php } else { ?>
<div class="all-around all-around-non">
<div class="float-on-left">
<div class="ignore_img"><input type="hidden" name="update_staffs_id[]" value="<?php echo $staff_update->id; ?>"></div>
<?php echo $staff_update->name; ?>
</div>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
I'm saving class in localStorage. And then user edits value in field and hes out off that field, I update that information with ajax
$('.'+localStorage.getItem("formId")+' input, .'+localStorage.getItem("formId")+' textarea').blur(function(event) {
var updateStaffId = $("."+localStorage.getItem("formId")+" .all-around-on input[name='update_staffs_id[]']").map(function(){return $(this).val();}).get();
var updateCategoriesId = $("."+localStorage.getItem("formId")+" select[name=update_services_category] option:selected").map(function(){return $(this).val();}).get();
var formData = {
'from' : 'serviceUpdate',
'user_id' : '<?php echo $mainUser->id; ?>',
'services_id' : localStorage.getItem("formId"),
'update_services_name' : $('.'+localStorage.getItem("formId")+' input[name=update_service_name]').val(),
'update_services_description' : $('.'+localStorage.getItem("formId")+' textarea[name=update_service_description]').val(),
'update_services_price' : $('.'+localStorage.getItem("formId")+' input[name=update_service_price]').val(),
'update_services_duration' : $('.'+localStorage.getItem("formId")+' input[name=update_service_duration]').val(),
'update_services_category' : updateCategoriesId,
'update_services_staff' : updateStaffId
};
$.ajax({
type : 'POST',
url : 'ajax/ServicesAjax.php',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
if(data['success'] == true) {
toastr.success("Information updated successfuly!", "Services");
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
The problem is that it's only works with last row. First row, second, 5 , 10 then opens information and edit field value, on blur it don't work. But last row works perfectly. Where can the problem be ?
UPDATED
PROBLEM SOLVE, I add my ajax in $('tr').click and change localStore with var servicesUpdateId = $(this).attr('data');. Maybe the problem was localStore. But in console, it always shows true value.
Replace
$('.'+localStorage.getItem("formId")+' input, .'+localStorage.getItem("formId")+' textarea').blur(function(event) {
with
$('.'+localStorage.getItem("formId")+' input, .'+localStorage.getItem("formId")+' textarea').on("blur",function(event) {
As .blur() functions is bind only with the elements which are loaded for the first time during page load.
But when you make html new elements in an existing page using ajax you need to bind the event again but this looks a boring task.
For this use jQuery.on() , and pass event name as first param, and rest same as .bind()/.click() or any other event functions.
So its better to use jQuery.on("eventName").
PROBLEM SOLVE, I add my ajax in $('tr').click and change localStore with var servicesUpdateId = $(this).attr('data');. Maybe the problem was localStore. But in console, it always shows true value

Categories