I am new beginer in jquery/ajax, working on a simple Ajax / Jquery html table - MySql. Everything works except 'Click to order' a field. Upon clicking a column heading (expecting to get ordered on this field), it gets ordered on the previous column/field. I made some adjustments, but still the same. The original codes were received from phpzag.com.
<?php
include('inc/header.php');
?>
<title>phpzag.com : Demo Live Add Edit Delete datatables Records with Ajax, PHP and MySQL</title>
<?php //include('inc/container.php');
$Col0 = "id";
$Col1 = "Topic";
$Col2 = "FileName";
$Col3 = "Size";
$Col4 = "Created";
$Col5 = "Modified";
$Col6 = "Folder";
?>
<div class="container contact">
<h2>Example: Live Add Edit Delete datatables Records with Ajax, PHP and MySQL</h2>
<div class="col-lg-10 col-md-10 col-sm-9 col-xs-12">
<div class="panel-heading">
<div class="row">
<div class="col-md-10">
<h3 class="panel-title"></h3>
</div>
<div class="col-md-2" align="right">
<!--- <button type="button" name="add" id="addRecord" class="btn btn-success">Add New Record</button> <!-- Original--->
<button type="button" name="add" id="addRtf" class="btn btn-success">Add New WordPad</button> <!--- Manoj --->
</div>
</div>
</div>
<table id="recordListing" class="table table-bordered table-striped"> <!-- ManojComment View page + update/close button --->
<thead>
<tr>
<!---<th>#</th> --->
<!---<th><?php //echo $Col0; ?></th> --->
<th><?php echo $Col1; ?></th>
<th><?php echo $Col2; ?></th>
<th><?php echo $Col3; ?></th>
<th><?php echo $Col4; ?></th>
<th><?php echo $Col5; ?></th>
<th><?php echo $Col6; ?></th>
<th>#</th>
<!--- <th></th> //Manoj removed - avoid del/update buttona
<th></th> -->
<th></th>
</tr>
</thead>
</table>
</div>
<div id="recordModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="recordForm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Edit Record</h4>
</div>
<div class="modal-body"> <!--- ManojComment EDIT modal page --->
<div class="form-group">
<label for="<?php echo $Col0; ?>" class="control-label"><?php echo $Col0; ?></label>
<input type="text" class="form-control" id="<?php echo $Col0; ?>" name="<?php echo $Col0; ?>" placeholder="<?php echo $Col0; ?>" required>
</div>
<div class="form-group">
<label for="<?php echo $Col1; ?>" class="control-label"><?php echo $Col1; ?></label>
<input type="text" class="form-control" id="<?php echo $Col1; ?>" name="<?php echo $Col1; ?>" placeholder="<?php echo $Col1; ?>" required>
</div>
<div class="form-group">
<label for="<?php echo $Col2; ?>" class="control-label"><?php echo $Col2; ?></label>
<input type="number" class="form-control" id="<?php echo $Col2; ?>" name="<?php echo $Col2; ?>" placeholder="<?php echo $Col2; ?>">
</div>
<div class="form-group">
<label for="<?php echo $Col3; ?>" class="control-label"><?php echo $Col3; ?></label>
<input type="text" class="form-control" id="<?php echo $Col3; ?>" name="<?php echo $Col3; ?>" placeholder="<?php echo $Col3; ?>" required>
</div>
<div class="form-group">
<label for="<?php echo $Col4; ?>" class="control-label"><?php echo $Col4; ?></label>
<textarea class="form-control" rows="5" id="<?php echo $Col4; ?>" name="<?php echo $Col4; ?>"></textarea>
</div>
<div class="form-group">
<label for="<?php echo $Col5; ?>" class="control-label"><?php echo $Col5; ?></label>
<input type="text" class="form-control" id="<?php echo $Col5; ?>" name="<?php echo $Col5; ?>" placeholder="<?php echo $Col5; ?>">
</div>
<div class="form-group">
<label for="<?php echo $Col6; ?>" class="control-label"><?php echo $Col6; ?></label>
<input type="text" class="form-control" id="<?php echo $Col6; ?>" name="<?php echo $Col6; ?>" placeholder="<?php echo $Col6; ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="id" id="id" />
<input type="hidden" name="action" id="action" value="" />
<input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php include('inc/footer.php');?>
Ajax_action.php
<?php
include_once 'config/Database.php';
include_once 'class/Records.php';
$database = new Database();
$db = $database->getConnection();
$record = new Records($db);
if(!empty($_POST['action']) && $_POST['action'] == 'listRecords') {
$record->listRecords();
}?>
Database.php
<?php
class Database{
private $host = 'localhost';
private $user = 'root';
private $password = "dd";
private $database = "dd";
public function getConnection(){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
} else {
return $conn;
}
}
}
Ajax.js
$(document).ready(function(){
var dataRecords = $('#recordListing').DataTable({
"lengthChange": false,
"processing":true,
"serverSide":true,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
"order":[],
"ajax":{
url:"ajax_action.php",
type:"POST",
data:{action:'listRecords'},
dataType:"json"
},
/*"columnDefs":[
{
"targets":[0, 6, 7],
"orderable":false,
},
],*/
"pageLength": 100
});
Records.php
class Records {
private $recordsTable = 'files';
public $id;
public $Topic;
public $FileName;
public $Size;
public $Created;
public $Modified;
public $Folder;
private $conn;
public function __construct($db){
$this->conn = $db;
}
public function listRecords(){
$Col0 = "id";
$Col1 = "Topic";
$Col2 = "FileName";
$Col3 = "Size";
$Col4 = "Created";
$Col5 = "Modified";
$Col6 = "Folder";
$sqlQuery = "SELECT * FROM ".$this->recordsTable." ";
if(!empty($_POST["search"]["value"])){
$sqlQuery .= 'where('.$Col0.' LIKE "%'.$_POST["search"]["value"].'%" ';
$sqlQuery .= ' OR '.$Col1 .' LIKE "%'.$_POST["search"]["value"].'%" ';
$sqlQuery .= ' OR '.$Col2 .' LIKE "%'.$_POST["search"]["value"].'%" ';
$sqlQuery .= ' OR '.$Col3 .' LIKE "%'.$_POST["search"]["value"].'%" ';
$sqlQuery .= ' OR '.$Col4 .' LIKE "%'.$_POST["search"]["value"].'%" ';
$sqlQuery .= ' OR '.$Col5 .' LIKE "%'.$_POST["search"]["value"].'%" ';
$sqlQuery .= ' OR '.$Col6 .' LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(!empty($_POST["order"])){
$sqlQuery .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$sqlQuery .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$stmt = $this->conn->prepare($sqlQuery);
$stmt->execute();
$result = $stmt->get_result();
$stmtTotal = $this->conn->prepare("SELECT * FROM ".$this->recordsTable);
$stmtTotal->execute();
$allResult = $stmtTotal->get_result();
$allRecords = $allResult->num_rows;
$displayRecords = $result->num_rows;
$records = array();
while ($record = $result->fetch_assoc()) {
$rows = array();
//$rows[] = ucfirst($record[$Col1]);//original
$rows[] = $record[$Col1];//manoj as order not working properly, test
$rows[] = $record[$Col2];
$rows[] = $record[$Col3];
$rows[] = $record[$Col4];
$rows[] = $record[$Col5];
$rows[] = $record[$Col6];
$rows[] = $record[$Col0];
//$rows[] = '<button type="button" name="update" id="'.$record["id"].'" class="btn btn-warning btn-xs update">Update</button>'; //original
//$rows[] = '<button type="button" name="delete" id="'.$record["id"].'" class="btn btn-danger btn-xs delete" >Delete</button>'; //Original
$rows[] = '<button type="button" name="open" id="'.$record["id"].'" class="btn btn-warning btn-xs open" >Open</button>';
$records[] = $rows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"iTotalRecords" => $displayRecords,
"iTotalDisplayRecords" => $allRecords,
"data" => $records
);
echo json_encode($output);
}
Related
I have a mysql data which I call to display to my PHP table and then for example I clicked the username01, I wanted to call the other columns of that username01 (e.g. password01, id01) to display to my modal fields.
Here's my code:
PHP
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" ?> <?php echo "<font color='blue'>" . $row['ipaddress'] . "</font></td>";
echo "<td>" . $row['name'] . "</td>";
Modal
<?php
include 'includes\dbconn.php';
$query = mysqli_query($conn,"SELECT * from devopstbl where id=$id");
$ipaddress = $row['ipaddress'];
$name = $row['name'];
$department = $row['department'];
?>
<div id="id01" class="modal">
<form class="modal-content animate" method="GET" action="ipaddress.php">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Exit">×</span>
<img src="images/avatar.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="ipaddress"><b>Username <?php echo $username; ?></b></label>
<input type="text" pattern="[a-zA-Z0-9\s]+" name="username" value="<?php echo $ipaddress; ?>" required>
Apparently.. the $id only gets the id01 even i clicked the other data like id02 etc. and does not get its other columns like username01 password01..
Am i missing something?
Put yout Modal-part to while loop.
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$username = $row['username'];
$ipaddress = $row['ipaddress'];
$name = $row['name'];
echo '<tr>
<td>
<font color="blue">'.$ipaddress.'</font>
<div id="id'.$id.'" class="modal">
<form class="modal-content animate" method="GET" action="ipaddress.php">
<div class="imgcontainer">
<span onclick="document.getElementById(\'id'.$id.'\').style.display=\'none\'" class="close" title="Exit">×</span>
<img src="images/avatar.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="ipaddress"><b>Username '.$username.'</b></label>
<input type="text" pattern="[a-zA-Z0-9\s]+" name="username" value="'.$ipaddress.'" required>
</div>
</form>
</div>
</td>
<td>'.$name.'</td>
';
}
Assigning php
if(isset($_SESSION['email'])) {
$login = $_SESSION['email'];
$conn = mysqli_connect("localhost", "root", "demo1234", "fromayu");
$con = mysqli_connect("localhost", "root", "demo1234", "fromayu");
$i = 0;
$rowsperpage=2;
$get_user = "select * from users where email='$login'";
$run_user = mysqli_query($con, $get_user);
$row=mysqli_fetch_array($run_user);
$user_id = $row['id'];
$user_name = $row['name'];
if (isset($_REQUEST['page'])) {
$page = $_REQUEST['page'];
$page=$page - 1;
$getuserenterpage=$page * $rowsperpage;
$get_posts = "select * from anotice ORDER BY 1 DESC LIMIT $getuserenterpage,$rowsperpage";
$run_posts = mysqli_query($conn, $get_posts);
}else{
$get_post = "select * from anotice ORDER BY 1 DESC LIMIT 0,2";
$run_posts = mysqli_query($conn, $get_post);
}
while ($row_posts=mysqli_fetch_array($run_posts)) {
$edit_id1 = $row_posts['id'];
$title = $row_posts['title'];
$image = $row_posts['image'];
$desc = substr($row_posts['description'],0,150);
$category = $row_posts['category'];
$batchid=$row_posts['batch_id'];
$dbatch=$row_posts['batch'];
$username=$row_posts['notice_by'];
$date = date('Y-m-d', strtotime($row_posts['date']));
?>
Using buttons and loading contents.Modal loads perfectly fine but when I want to click on textarea inside modal, It won`t respond, another modal has been loaded hidden on background.
<div class="row-fluid">
<div class="span12">
<div class="media user">
<div class="media-body">
<h2 class="media-title" data-target="#popup<?php echo $i; ?>_<?php echo $edit_id1; ?>"><strong>Title: <?php echo $title; ?></strong>
</h2>
<i class="icon-trash"></i>
<button data-target="#popup<?php echo $i; ?>_<?php echo $edit_id1; ?>" data-toggle="modal" class='pull-right text-xs m-t-sm btn btn-info'><i class="icon-edit"></i></button>
<p>
<div class="pull-left">
<img src="../../storage/teacher_submitted_notice/images/<?php echo $image; ?>" width="120" height="120"/> </div>
<small class="muted">Description: <?php echo $desc; ?>...<a class="text-info" href="#">Read More</a></small></p>
<em class="pull-right text-xs"> Posted on <span class="text-default"><strong><?php echo $date; ?></strong></span> for <span class="text-default"><strong><?php echo $category; ?></strong></em>
</div>
</div>
</div>
</div>
Starting modal with respective ids. It shows but it wont respond inside modal when i clicked in textarea or title. Only works when i use tab from keyboard
<br />
<div class="modal fade" id="popup<?php echo $i; ?>_<?php echo $edit_id1; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Notice</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" hidden="hidden">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<form method="POST" enctype="multipart/form-data">
<label for="recipient-name" class="col-form-label">Title</label>
<input style="position:relative;width:485px;" type="text" name="title" id="title" class="form-control" value="<?php echo $title; ?>">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Description</label>
<textarea style="position:relative;width:485px;" rows="4" cols="6" name="description" id="description" class="form-control"><?php echo $desc; ?></textarea>
</div>
<select class="form-control" name="selectCategory" id="selectCategory" onclick="javascript:$('#selectCategory').change(function () {
var selected_option = $('#selectCategory').val();
if (selected_option === 'student') {
$('#cmbbatch').show();
}
if (selected_option === 'teacher') {
$('#cmbbatch').hide();
}
});">
<option>Choose Category</option>
<option value="teacher">Teacher</option>
<option value="student">Student</option>
</select>
<select style="position:relative;left:55px;" class="form-control" name="cmbBatch" id="cmbbatch">
<option value="batch">Choose Batch</option>
<?php
$query = "SELECT * FROM batch";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$batch= $row['batch'];
?>
<option value="<?php echo $id; ?>"><?php echo $batch; ?></option>
<?php
}
?>
</select><br>
<input type="file" name="image" id="image" required="required">
<img style="position:relative;left:22px;" src="../../storage/teacher_submitted_notice/images/<?php echo $image; ?>" height="120" width="120" name="image">
<input type="hidden" name="notic_id" id="notic_id" value="<?php echo $edit_id1; ?>"/>
<input type="hidden" name="notice_by" id="notice_by" value="<?php echo $username; ?>"/>
<input type="hidden" name="edited_by" id="edited_by" value="<?php echo $user_name; ?>"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input type="submit" name="update" id="update" value="Update" onclick="javascript:document.getElementById('update').value='Updating!'"class="btn btn-info" />
</div>
</div>
</div>
<?php
$i++;
?>
</div>
</form>
<?php
}
include 'totalnoticepage.php';
?>
<?php
}else{
header('Location: ../../index.php');
}
?>
Problem solved by adding hide class
<div class="modal hide fade" id="popup<?php echo $i; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
This is my first time using multiple select options and add more field function in form. I have this form where I can enter multiple serialNumber and also add multiple accessories and quantity accordingly. But the only first selected serialNumber and accessories (and quantity) saved in my database.
So here is my HTML Form:
<form id="form1" name="form1" method="post" action="requisitionForm_process.php" onsubmit="return validateForm()" >
<div class="form-group">
<label for="DONO">DO. Number: </label>
<input class="form-control" id="DONO" name="DONO" placeholder="Place DO. Number Here" type="text"/>
</div>
<div class="form-group">
<label for="requestby">Request By: </label>
<select class="form-control" id="empCode" name="empCode">
<?php while ($row = mysqli_fetch_array($resultR)):;?>
<option value = <?php echo $row ['empCode']; ?>><?php echo $row ['empCode']; echo ":"; echo $row ['empName'];?></option>
<?php endwhile;
?>
</select>
</div>
<div class="form-group">
<label for="requestby">Customer: </label>
<select class="form-control" id="customerCode" name="customerCode">
<?php while ($row = mysqli_fetch_array($resultC)):;?>
<option value = <?php echo $row ['customerCode']; ?>><?php echo $row ['customerCode']; echo ":"; echo $row ['customerName'];?></option>
<?php endwhile;
?>
</select>
</div>
<div class="form-group"> <!-- Date input -->
<label class="control-label" for="dateOUT">Date:</label>
<input class="form-control" id="dateOUT" name="dateOUT" placeholder="DD/MM/YYY" type="text"/>
</div>
<div class="form-group">
<label for="categoryCode">Category: </label>
<select class="form-control" id="categoryCode" name="categoryCode">
<option value="new"> New Installation</option>
<option value="re">Re-installation</option>
</select>
</div>
<div class="form-group">
<label for="categoryCode">Product: </label>
<select class="form-control" id="productCode" name="productCode">
<?php while ($row = mysqli_fetch_array($result)):;?>
<option value = <?php echo $row ['productCode']; ?>><?php echo $row ['productCode']; echo ":"; echo $row ['productName'];?></option>
<?php endwhile;
?>
</select>
</div>
<div class="form-group">
<label for="serialNumber">Serial Number:</label><br>
<select id="serialNumber" name="serialNumber[]" multiple class="form-control" >
<?php while ($row = mysqli_fetch_array($resultSe)):;?>
<option value = <?php echo $row ['serialNumber']; ?>><?php echo $row ['serialNumber'];?></option>
<?php endwhile;?>
</select>
</div>
<table class="table table-bordered" id="item_table">
<tr>
<th>Select Accessories</th>
<th>Enter Quantity</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div class="form-group">
<input type="button" class="btn" id="checkBtn" name="return" value="Back" onClick="javascript: window.history.back(-1)";>
<input class="btn btn-primary" type="reset" value="Reset">
<input align="right" type="submit" class="btn btn-info" value="Submit Button">
</div>
</div>
</form>
And this is my PHP process:
<?php
if(isset($_POST["serialNumber"]))
{
$serialNumber = '';
foreach($_POST["serialNumber"] as $row)
{
$serialNumber .= $row . ', ';
}
$serialNumber = substr($serialNumber, 0, -2);
if(isset($_POST["categoryCode"]))
{
$connect = new PDO("mysql:host=localhost;dbname=ims", "root", "");
$DONO = $_POST["DONO"];
$empCode = $_POST["empCode"];
$customerCode = $_POST["customerCode"];
$categoryCode = $_POST["categoryCode"];
$productCode = $_POST["productCode"];
$dateOUT = date('Y-m-d', strtotime($_POST['dateOUT']));
for($count = 0; $count < count($_POST["accID"]); $count++)
{
$query = "INSERT INTO requisition (DONO, empCode, customerCode, dateOUT, categoryCode, productCode, serialNumber, quantityAcc, accID) VALUES (:DONO, :empCode, :customerCode, :dateOUT, :categoryCode, :productCode, :serialNumber, :quantityAcc, :accID) ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':DONO' => $DONO,
':empCode' => $empCode,
':customerCode' => $customerCode,
':dateOUT' => $dateOUT,
':categoryCode' => $categoryCode,
':productCode' => $productCode,
':serialNumber' => $serialNumber,
':quantityAcc' => $_POST["quantityAcc"][$count],
':accID' => $_POST["accID"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
}
?>
if(isset($_POST["test"]))
{
$serialNumber = '';
foreach($_POST["test"] as $row=>$value)
{
$serialNumber .= $value . ', ';
}
$serialNumber = substr($serialNumber, 0, -2);
}
Replace yor loop with this , before i was unable to html.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Well, for a good while I've now been stuck trying to figure out why most of my records are updating successfully while a certain few aren't. I've checked the php variable name/sql row names, ajax request and I don't see anything wrong. So here I am, hoping that someone can take a look at my code and help me figure out what's wrong.
Screenshot to show what I'm refering to.
Html/JS:
<div class="container">
<div class="page-header">
<h1>General Reservation
<small>Update, Delete</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="container-fluid">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Department/Group</th>
<th>On-site Contact</th>
<th>Phone</th>
<th>Email</th>
<th>Event Description</th>
<th>Setup Time</th>
<th>Number of Participants</th>
<th>Date</th>
<th>Start/End Time</th>
<th>Special Accommodations</th>
<th>Room</th>
<th>Room Style</th>
<th>Catering</th>
<th>Technical Equipment</th>
<th>Pre-Clean</th>
<th>On-clean</th>
<th>Post-Clean</th>
<th>Reserved Parkning</th>
<th>VIP</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/scripts.js"></script>
<script>
function viewGenData(){
$.ajax({
type: "GET",
url: "servergen.php",
success: function(data){
$('tbody').html(data);
}
});
}
function updateGenData(str){
var id = str;
var name = $('#name-'+str).val();
var dptGroup = $('#dptgroup-'+str).val();
var onSiteContact = $('#onsitecontact-'+str).val();
var phone = $('#phone-'+str).val();
var email = $('#email-'+str).val();
var eventDesc = $('#eventdesc-'+str).val();
var setUpTime = $('#setuptime-'+str).val();
var numOfParticipants = $('#partcnum-'+str).val();
var date = $('#date-'+str).val();
var startEndTime = $('#startendtime-'+str).val();
var specialAcc = $('#specialacc-'+str).val();
var room = $('#room-'+str).val();
var roomStyle = $('#roomstyle-'+str).val();
var catering = $('#catering-'+str).val();
var techEquip = $('#techequip-'+str).val();
var preClean = $('#preclean-'+str).val();
var postClean = $('#postclean-'+str).val();
var onClean = $('#onclean-'+str).val();
var rsvParking = $('#rsvparking-'+str).val();
var vip = $('#vip-'+str).val();
$.ajax({
type: "POST",
url: "servergen.php?p=edit",
data: "name=" + name + "&department=" + dptGroup + "&contact=" + onSiteContact + "&phone=" +
phone + "&email=" + email + "&description=" + eventDesc + "&setuptime=" + setUpTime + "&numberofparticipants=" + numOfParticipants +
"&date=" + date + "&startendtime=" + startEndTime + "&specialacc=" + specialAcc + "&room=" + room + "&roomstyle=" + roomStyle +
"&catering=" + catering + "&techequipment=" + techEquip + "&preclean=" + preClean + "&postclean=" + postClean + "&onclean=" + onClean +
"&rsvparking=" + rsvParking + "&vip=" + vip + "&id=" + id,
success: function(data){
viewGenData();
}
});
}
function deleteGenData(str){
var id = str;
$.ajax({
type: "GET",
url: "servergen.php?p=del",
data: "id="+id,
success: function(data){
viewGenData();
}
});
}
Php/mySQL:
<?php
include("db.php");
$page = isset($_GET['p'])?$_GET['p']:'';
if($page=='edit'){
$id = $_POST['id'];
$name = $_POST['name'];
$dptGroup = $_POST['dptgroup'];
$onSiteContact = $_POST['onsitecontact'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$eventDesc = $_POST['eventdesc'];
$setUpTime = $_POST['setuptime'];
$numOfParticipants = $_POST['partcnum'];
$date = $_POST['date'];
$startEndTime = $_POST['startendtime'];
$specialAcc = $_POST['specialacc'];
$room = $_POST['room'];
$roomStyle = $_POST['roomstyle'];
$catering = $_POST['catering'];
$techEquip = $_POST['techequip'];
$preClean = $_POST['preclean'];
$postClean = $_POST['postclean'];
$onClean = $_POST['onclean'];
$rsvParking = $_POST['rsvparking'];
$vip = $_POST['vip'];
$stmt = $db->prepare("update reservations set req_name=?, dept_group=?, onsite_contact=?, phone_num=?, email=?, event_description=?, setup_time=?, num_participants=?, date=?, start_end_time=?, notes=?, room=?, room_style=?, catering=?, tech_equip=?, pre_clean=?, post_clean=?, on_clean=?, reserved_parking=?, vip=? where id=?");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$dptGroup);
$stmt->bindParam(3,$onSiteContact);
$stmt->bindParam(4,$phone);
$stmt->bindParam(5,$email);
$stmt->bindParam(6,$eventDesc);
$stmt->bindParam(7,$setUpTime);
$stmt->bindParam(8,$numOfParticipants);
$stmt->bindParam(9,$date);
$stmt->bindParam(10,$startEndTime);
$stmt->bindParam(11,$specialAcc);
$stmt->bindParam(12,$room);
$stmt->bindParam(13,$roomStyle);
$stmt->bindParam(14,$catering);
$stmt->bindParam(15,$techEquip);
$stmt->bindParam(16,$preClean);
$stmt->bindParam(17,$postClean);
$stmt->bindParam(18,$onClean);
$stmt->bindParam(19,$rsvParking);
$stmt->bindParam(20,$vip);
$stmt->bindParam(21,$id);
if($stmt->execute()){
echo "Success, data updated.";
} else{
echo "Failed, dated not updated.";
}
} else if($page=='del'){
$id = $_GET['id'];
$stmt = $db->prepare("delete from reservations where id=?");
$stmt->bindParam(1, $id);
if($stmt->execute()){
echo "Success, data deleted.";
} else{
echo "Failed to delete data.";
}
} else{
$stmt = $db->prepare("select * from reservations order by id desc");
$stmt->execute();
while($row = $stmt->fetch()){
?>
<tr>
<td><?php echo $row['req_name']?></td>
<td><?php echo $row['dept_group']?></td>
<td><?php echo $row['onsite_contact']?></td>
<td><?php echo $row['phone_num']?></td>
<td><?php echo $row['email'] ?></td>
<td><?php echo $row['event_description'] ?></td>
<td><?php echo $row['setup_time']?></td>
<td><?php echo $row['num_participants']?></td>
<td><?php echo $row['date']?></td>
<td><?php echo $row['start_end_time']?></td>
<td><?php echo $row['notes']?></td>
<td><?php echo $row['room']?></td>
<td><?php echo $row['room_style']?></td>
<td><?php echo $row['catering']?></td>
<td><?php echo $row['tech_equip']?></td>
<td><?php echo $row['pre_clean']?></td>
<td><?php echo $row['post_clean']?></td>
<td><?php echo $row['on_clean']?></td>
<td><?php echo $row['reserved_parking']?></td>
<td><?php echo $row['vip']?></td>
<td>
<button class="btn btn-warning" data-toggle="modal" data-target="#edit-<?php echo $row['id'] ?>">Update</button>
<!-- Modal -->
<div class="modal fade" id="edit-<?php echo $row['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="editLabel-<?php echo $row['id'] ?>">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editLabel-<?php echo $row['id'] ?>">Update Data</h4>
</div>
<form>
<div class="modal-body">
<input type="hidden" id="<?php echo $row['id'] ?>" value="<?php echo $row['id'] ?>">
<div class="form-group">
<label for="name-">Name of Requestor </label>
<input type="text" class="form-control" id="name-<?php echo $row['id'] ?>" value="<?php echo $row['req_name'] ?>" />
</div>
<div class="form-group">
<label for="phone-">Phone Number</label>
<input type="tel" class="form-control" id="phone-<?php echo $row['id'] ?>" value="<?php echo $row['phone_num'] ?>"" />
</div>
<div class="form-group">
<label for="setuptime-">Facilities/Catering Set-up time
</label>
<input type="text" class="form-control" id="setuptime-<?php echo $row['id'] ?>" value="<?php echo $row['setup_time'] ?>" />
</div>
<div class="form-group">
<label for="dptgroup-">Department/Group</label>
<input type="text" class="form-control" id="dptgroup-<?php echo $row['id'] ?>" value="<?php echo $row['dept_group'] ?>" />
</div>
<div class="form-group">
<label for="email-">Email Address</label>
<input type="email" class="form-control" id="email-<?php echo $row['id'] ?>" value="<?php echo $row['email'] ?>" />
</div>
<div class="form-group">
<label for="partcnum-">Number of Participants</label>
<input type="text" class="form-control" id="partcnum-<?php echo $row['id'] ?>" value="<?php echo $row['num_participants'] ?>" />
</div>
<div class="form-group">
<label for="onsitecontact-">On-site Contact</label>
<input type="text" class="form-control" id="onsitecontact-<?php echo $row['id'] ?>" value="<?php echo $row['onsite_contact'] ?>" />
</div>
<div class="form-group">
<label for="eventdesc-">Description of the Event</label>
<textarea id="eventdesc-<?php echo $row['id'] ?>" class="form-control" rows="5" cols="25" value="<?php echo $row['event_description'] ?>"><?php echo $row['event_description']?></textarea>
</div>
<div class="form-group">
<label for="date-">Date</label>
<input type="text" class="form-control" id="date-<?php echo $row['id'] ?>" value="<?php echo $row['date'] ?>" />
</div>
<div class="form-group">
<label for="startendtime-">Start/End Time (AM/PM)</label>
<input type="text" class="form-control" id="startendtime-<?php echo $row['id'] ?>" value="<?php echo $row['start_end_time'] ?>" />
</div>
<div class="form-group">
<label for="specialacc-">Special accommodations, notes or additional requirements</label>
<textarea id="specialacc-<?php echo $row['id'] ?>" class="form-control" rows="5" cols="25" value="<?php echo $row['notes'] ?>"><?php echo $row['notes']?></textarea>
</div>
<div class="form-group">
<label for="catering-">Is catering needed?</label>
<input type="text" class="form-control" id="catering-<?php echo $row['id'] ?>" value="<?php echo $row['catering'] ?>" />
</div>
<div class="form-group">
<label for="techequip-">Is technical equipment needed?</label>
<input type="text" class="form-control" id="techequip-<?php echo $row['id'] ?>" value="<?php echo $row['tech_equip'] ?>" />
</div>
<div class="form-group">
<label for="preclean-">Is pre-clean up needed?</label>
<input type="text" class="form-control" id="preclean-<?php echo $row['id'] ?>" value="<?php echo $row['pre_clean'] ?>" />
</div>
<div class="form-group">
<label for="onclean-">Is clean up during the event needed?</label>
<input type="text" class="form-control" id="onclean-<?php echo $row['id'] ?>" value="<?php echo $row['on_clean'] ?>" />
</div>
<div class="form-group">
<label for="postclean-">Is post clean up needed?</label>
<input type="text" class="form-control" id="postclean-<?php echo $row['id'] ?>" value="<?php echo $row['post_clean'] ?>" />
</div>
<div class="form-group">
<label for="rsvparking-">Is reserved parking needed?</label>
<input type="text" class="form-control" id="rsvparking-<?php echo $row['id'] ?>" value="<?php echo $row['reserved_parking'] ?>" />
</div>
<div class="form-group">
<label for="vip">Will there be a very important person will be in attendance (dignitaries, elected officials, high profile)?</label>
<input type="text" class="form-control" id="vip-<?php echo $row['id'] ?>" value="<?php echo $row['vip'] ?>" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" onclick="updateGenData(<?php echo $row['id'] ?>)" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
<button onclick="deleteGenData(<?php echo $row['id'] ?>)" class="btn btn-danger" style="width: 73.94px; margin-top: 2px">Delete</button>
</td>
</tr>
<?php
}
}
?>
First change ajax data section from:
data: "name=" + name + "&department=" + dptGroup + "&contact=" + onSiteContact + "&phone="
to:
data: {"name": name, department: dptGroup , [...]}
Second: You will always be doing the js code from the success section. If an error occurred, send the error status, eg:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
And last: Show yourself error messages. It should define DEBUG constant and depending on the settings display more or less information about the error.
How can I pass the value of order_id from order.php to ordermodal.php, So I can use it in my query.
This is the order.php
UI of order.php
<?php
session_start();
$order_id = $_SESSION['order_id'];
if (!isset($_SESSION['user_id']))
{
header("Location: index.php");
}
$_SESSION['navMenu'] = "order";
ini_set('display_errors', 'On');
require_once 'includes/database.php';
include_once 'system_menu.php';
include_once 'ordermodal.php';
$sql2 = "SELECT * FROM cart_tbl";
$sql = "SELECT * FROM order_tbl WHERE order_status = 'Accepted' or order_status = 'Dispatched' or order_status = 'Pending' ORDER BY order_datetime DESC";
/*** * SET UP COMBO BOX FOR SEARCH */
$comboBox = isset($_REQUEST['comboBoxVal']) ? trim($_REQUEST['comboBoxVal']) : '';
$search_by = isset($_REQUEST['search_by']) ? addslashes($_REQUEST['search_by']) : 0;
$users = null;
if ($comboBox != '') { switch ($search_by) {
case 1://Order ID
$sql .= " WHERE order_id LIKE '%{$comboBox}%' ";
break;
}
}
$carts = mysqli_query(connection(), $sql2);
$orders = mysqli_query(connection(), $sql);
$search_filters = array(1 => 'Order ID');
/*** * END SET UP COMBO BOX */ ?>
<html>
<head>
<title>ORDERS</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
body {
background:url(images/jerica.jpg)fixed no-repeat center;
background-size:cover;
}
.asd {
color: white;
}
</style>
</head>
<body>
<?php
if (isset($_SESSION['message'])) {
$message = $_SESSION['message']; unset($_SESSION['message']);
}
else {
$message = "";
}
?> <div class="container" >
<h1 class="asd">Orders</h1>
</div> <div class="container" >
<div class="panel panel-default" >
<div class="panel-heading"> <form method="post"> <div class="input-group">
<div class="input-group-addon"> <select name="search_by">
<?php
foreach ($search_filters as $key => $value): ?>
<option value="<?= $key ?>" <?= $key == $search_by ? 'selected' : '' ?> > <?= $value ?> </option>
<?php
endforeach;
?>
</select>
</div>
<input type="search" name="comboBoxVal" value="<?= $comboBox ?>" class="form-control" placeholder="Search">
</div>
</form>
</div>
<div class="panel-body">
<?php
if ($message != ''): ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"> ×</span></button>
<?= $message ?> </div>
<?php endif; ?>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Order ID</th>
<th>User ID</th>
<th>Order Date</th>
<th>Order Time</th>
<th>Delivery Charge</th>
<th>Total Amount</th>
<th>Address</th>
<th>Coordinates</th>
<th>Driver Number</th>
<th>Order Status</th>
<th>Action</th>
</tr>
</thead>
<?php
/*** * DISPLAY TABLE */
?>
<tbody>
<?php if ($orders): ?>
<?php
while ($order = mysqli_fetch_array($orders, MYSQLI_BOTH)):
?>
<?php
$order_datetime = $order['order_datetime'];
$date = date('Y-m-d', strtotime($order_datetime));
$time = date('H:i:s', strtotime($order_datetime));
?>
<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'] ?>', '<?= $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, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("titleModal").innerHTML = "viewOrder";
document.getElementsByName("order_id")[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("driver_number")[0].setAttribute("value", driver_number);
document.getElementsByName("order_status")[0].setAttribute("value", order_status);
document.getElementsByName("viewOrder")[0].setAttribute("name", "viewOrder");
/*x = document.getElementsByName("order_status").value;
if(x == "Accepted"){
document.getElementsByName("submitAccept").disabled = true;
}*/
}
</script?
</body>
</html>
And this is the ordermodal.php
UI of ordermodal.php
<?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">
<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"></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">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="driver_number" id="driver_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
// This is where I want to get the value of oder_id from order.php page
$sql = "SELECT food_name, special_request, quantity, amount
FROM cart_tbl
WHERE order_id=$order_id";
$result = mysqli_query(connection(), $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>
<tbody>
</div>
<div class="modal-footer">
<button type="submit" name="showOrder" id="showOrder" class="btn btn-secondary" onclick="" > Show Order </button>
<button type="submit" 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="submit" name="submitSent" class="btn btn-primary"onclick="if(!confirm('Are you sure you want to send order?')){return false;}" >Sent</button>
<button type="submit" 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['showOrder'])){
$order_id = trim(addslashes($_POST['order_id']));
}
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(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Accepted"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
if(isset($_POST['submitSent'])){
$order_id = trim(addslashes($_POST['order_id']));
$query = "UPDATE order_tbl SET `order_status`='Dispatched' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Dispatched"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "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(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Cancelled"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
?>
</div>
</form>
</div>
</div>
</div>
So the function of this as the moment is when clicked the view order the value of the order_id from order.php didnt get, you need first to click the button inside the ordermodal.php(accept,send,cancel) in order to get the value of order_id.
"When I click the view order, I'll get right away the value of order_id so that I can use it in my sql query. This is what supposed to be the real output."
Hope you guys can help me, I stacked at this error for a couple of days already. TIA!
Couldn't you still use the session var you did in the first chunk...unless you are reseting that value - but didn't see that...
Alternatively... the url you are calling to get the url for the modal you could put a query param of OID=# and than do the typical...
$orderID = $_GET['old'] ? $_GET['old'] : $_POST['old']; // not sure if your posting or just doing a get....
Also no sure if your pulling this in through an iframe or what not but either way query param or session var should work.
Hope this helps.