Ajax Mysql PHP How to show $_SESSION arrays result into DIV - php

My friends,
I´m facing some hard trouble with Ajax & PHP integration. I have a simple code as below that returns the data from database and shows into div class="item-list". When the user puts the quantity and clicks on submit button, the selected item is uploaded into div class="returned", like the "add item to cart" function. The code is working as well (add & remove from list), but only with refresh on page.
I saw many examples on web and I tried to adapt them to my code (today is my third day of fighting), but with no success. Could you please show to me a way to load the selected items into div class="returned" without refresh on page?
Best regards & thanks a lot!
<?php
session_start();
if(isset($_POST["add_to_table"])){
if(isset($_SESSION["dynamic_list"])){
$item_array_id = array_column($_SESSION["dynamic_list"], "item_id");
if(!in_array($_GET["idproduct"], $item_array_id)){
$count = count($_SESSION["dynamic_list"]);
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][$count] = $item_array;
}else{
echo'<script>alert("Item added!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}else{
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][0] = $item_array;
}
}
if(isset($_GET["action"])){
if($_GET["action"] == "delete"){
foreach($_SESSION["dynamic_list"] as $list => $values){
if($values["item_id"] == $_GET["idproduct"]){
unset($_SESSION["dynamic_list"][$list]);
echo'<script>alert("Item removed!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}
}
}
?>
<?php include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<div id="product_table">
<form method="post" action="intransit.php?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span><img src="images/<?php echo $row["image"]; ?>" alt="motor" width="80" height="80" /></span>
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty" />
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>" />
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>" />
<input type="submit" name="add_to_table" value="Add Item" />
</form>
</div><!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<table>
<tr>
<th>Model</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
<?php
if(!empty($_SESSION["dynamic_list"])){
$total = 0;
foreach($_SESSION["dynamic_list"] as $list => $values){
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td>Remove</td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2);?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
<?php include"footer.php" ?>

I tried to make example less complicated and to make it work with code you already created.
if (isset($_POST['got_model'])) {
$_SESSION["dynamic_list"][$_GET["idproduct"]] = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
return show_dynamic_list();
}
if (isset($_POST["action"]) && $_POST["action"] == "delete") {
unset($_SESSION["dynamic_list"][$_POST["idproduct"]]);
return show_dynamic_list();
}
function show_dynamic_list(){
?>
<table>
<tr><th>Model</th><th>Qty</th><th>Price</th><th>Total</th><th>Action</th></tr>
<?php
$total = 0;
foreach ($_SESSION["dynamic_list"] as $list => $values) {
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td>
<form action="" method="post" class="delete_form">
<input type="hidden" name="idproduct" value="<?php echo $values["item_id"]; ?>"/>
<input type="hidden" name="action" value="delete"/>
<input type="submit" value="Remove">
</form>
</td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
</table>
<?php
}
include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<div id="product_table_<?php echo $row["idproduct"]; ?>">
<form method="post" action="?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty"/>
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>"/>
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>"/>
<input type="submit" name="add_to_table" value="Add Item"/>
</form>
</div><<!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<?php show_dynamic_list(); ?>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$('body').on('submit','#moviment form,.delete_form',function (event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type:'post',
url: form.attr('action'),
data: form.serialize(),
dataType:'html'
}).done(function (data) {
$('.returned').html(data);
}).fail(function (data) {
// error
});
});
});
</script>
<?php include"footer.php";

Related

How to call alert after ajax success data request?

view:
<script>
$(document).ready(function(){
$(".user_id").click(function(){
jid = $(".jid").attr('id');
var uids = [];
$("input[name='user_id']").map(function() {
uids.push({id: this.id, value: this.checked ? 1 : 0});
});
$.ajax({
type:"POST",
data:{"jid":jid, "uid":uids},
url:"<?php echo base_url(); ?>shortlist",
success:function(data){
$(".short_emp").html(data);
}
});
});
$(document).on('click' ,".user_idd" , function(){
jidd = $(".jidd").attr('id');
var uidss = [];
$("input[name='user_idd']").map(function() {
uidss.push({id: this.id, value: this.checked ? 1 : 0});
});
$.ajax({
type:"POST",
data:{"jidd":jidd, "uidss":uidss},
url:"<?php echo base_url(); ?>interview",
success:function(data){
alert(data);
//$(".short_interview").html(data);
}
});
});
});
</script>
<div class="wizard_horizontal">
<h2>Received</h2>
<section>
<table class="table table-hover js-basic-example dataTable table-custom m-b-0">
<thead>
<tr>
<th>Name</th>
<th>Shortlist</th>
</tr>
</thead>
<tbody>
<?php
$this->db->select('*');
$this->db->from('upload_detail');
$this->db->where('share_with_emp','1');
$sqll = $this->db->get();
if($sqll->num_rows() > 0)
{
$resultt = $sqll->result_array();
foreach($resultt as $roww)
{
?>
<tr>
<td>
<h6><?php echo $roww['fname']; ?></h6>
</td>
<td>
<div class="fancy-checkbox">
<label>
<input type="hidden" name="jid" class="jid form-control" id="<?php echo $roww['jid']; ?>"/>
<input type="checkbox" name="user_id" id="<?php echo $roww["uid"]; ?>" class="user_id" <?php if($roww['shortlist']=='1'){ echo 'checked'; }?>><span>Shortlist</span>
</label>
</div>
</td>
</tr>
<?php
}
}
else
{
echo "<p>No data Found</p>";
}
?>
</tbody>
</table>
</section>
<h2>Shortlisted</h2>
<section>
<table class="table table-hover js-basic-example dataTable table-custom m-b-0">
<thead>
<tr>
<th>Name</th>
<th>Shortlist</th>
</tr>
</thead>
<tbody class="short_emp">
<?php
$this->db->select('*');
$this->db->from('upload_detail');
$this->db->where('shortlist','1');
$sql_short = $this->db->get();
$result_short = $sql_short->result_array();
foreach($result_short as $fetch)
{
?>
<tr>
<td>
<h6><?php echo $fetch['fname']; ?></h6>
</td>
<td>
<div class="fancy-checkbox">
<label>
<input type="hidden" name="jidd" class="jidd form-control" id="<?php echo $fetch['jid']; ?>"/>
<input type="checkbox" name="user_idd" id="<?php echo $fetch["uid"]; ?>" class="user_idd" <?php if($fetch['interview']=='1'){ echo 'checked'; }?>><span>Shortlist</span>
</label>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</section>
</div>
controller:
<?php
public function shortlist()
{
$jid = $this->input->post('jid');
$uid = $this->input->post('uid');
foreach($uid as $user)
{
$data = array('shortlist'=> $user['value']);
$where = 'jid="'.$jid.'" and uid="'.$user['id'].'"';
$this->db->where($where);
$query = $this->db->update('upload_detail',$data);
}
if($query==true)
{
$this->db->select('*');
$this->db->from('upload_detail');
$where = "jid='".$jid."' and shortlist='1'";
$this->db->where($where);
$sql_short = $this->db->get();
if($sql_short->num_rows() > 0)
{
$result_short = $sql_short->result_array();
foreach($result_short as $fetch)
{
?>
<tr>
<td>
<h6><?php echo $fetch['fname']; ?></h6>
</td>
<td>
<div class="fancy-checkbox">
<label>
<input type="hidden" name="jidd" class="jidd form-control" id="<?php echo $fetch['jid']; ?>"/>
<input type="checkbox" name="user_idd" id="<?php echo $fetch["uid"]; ?>" class="user_idd" <?php if($fetch['interview']=='1'){ echo 'checked'; }?>><span>Shortlist</span>
</label>
</div>
</td>
</tr>
<?php
}
}
else
{
echo "<p>No data Found</p>";
}
}
else
{
echo "<p>Unable to Proceed</p>";
}
}
public function interview()
{
$jidd = $this->input->post('jidd');
$uidd= $this->input->post('uidss');
echo $jidd;
print_r($uidd);
}
?>
In my code, I have table first with heading Recieved where I got data. Now, what am I doing when I click on class="user_id" it run successfully and load content over $(.short_emp).html(data) which is the part of heading shortlist inside the <tbody class="short_emp"> but when I click on $(".user_idd").click(function(){ then no alert are showing I don't know why? So How can I resolve this issue? Please help me.
Thank You
try to add attribute data-id in an input field and call that in a function
<input type="checkbox" name="user_idd" id="<?php echo $fetch["uid"]; ?>" data-id="<?php echo $fetch["uid"]; ?>" class="user_idd" <?php if($fetch['interview']=='1'){ echo 'checked'; }?>><span>Shortlist</span>
$(document).on("click", ".user_idd", function(){
var attr = $(this).attr('data-id');
alert(attr);
});
hope it will work for you :)

Multiple Checkboxes Columns Updating Multiple SQL Rows

I've never had issues programming PHP SQL updates when updating multiple rows of data with multiple columns, but for some reason this section of coding is killing me as it is nothing more than checkboxes for the end user to check and/or uncheck. I've include portions of the code below as the full code is over 50+ columns wide of checkboxes and can range from 1-200 rows.
Everything displays/runs the way its supposed to but the updating isnt functioning properly ... example: if there is 5 rows (each with a unique trackingid) and I check the checkbox for the 4th row on update it says that the 1st checkbox was checked and NOT the 4th row.
<?php if (!isset($_POST['trackingid'])) { ?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="form"><input type="hidden" name="id" value="<?php echo $id; ?>">
<table class="table table-striped">
<thead>
<tr>
<td class="rotate-alt"></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt"><div><span>Glass</span></div></td>
<td class="rotate-alt"><div><span>Glass - SDL</span></div></td>
<td class="rotate-alt"><div><span>Mill - S&R</span></div></td>
</tr>
</thead>
<tbody>
<?php $result = sqlsrv_query($conn, "SELECT id, [Order Number], [Door Number], [Qty Display], [Interior or Exterior], [Style], Species_DD_Desc, [Mill Batch Nbr],
[Glass Completed], [Glass Completed By], [Glass STD Hrs], [SDL Completed], [SDL Completed By], [SDL STD Hrs],
[Mill Completed], [Mill Completed By], [Mill STD Hrs]
FROM PD_Tracking
WHERE [Order Number] = '$id'
ORDER BY [Door Number], [Qty Display], [Mill Batch Nbr]");
$i=0;
while ($list = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){ ?>
<tr>
<td class="center">
<input type="checkbox" onclick="$('input[id=\'selid<?php echo $i; ?>\']').attr('checked', this.checked);">
<input type="hidden" name="trackingid[]" value="<?php echo $list['id']; ?>">
</td>
<td class="center"><?php echo $list['Door Number']; ?></td>
<td class="center"><?php echo $list['Qty Display']; ?></td>
<td class="center"><?php echo $list['Interior or Exterior']; ?></td>
<td class="center"><?php echo $list['Style']; ?></td>
<td class="center"><?php echo $list['Species_DD_Desc']; ?></td>
<td class="center">
<?php if (($list['Glass STD Hrs']>0) && (!isset($list['Glass Completed']))){ ?>
<input type="checkbox" name="glass[]" id="selid<?php echo $i; ?>">
<?php } else if (($list['Glass STD Hrs']>0) && ($list['Glass Completed'] > ' ')){ ?>
<input type="checkbox" name="glass[]" checked="checked" id="selid<?php echo $i; ?>">
<?php } else { ?>
NR
<?php } ?>
</td>
<td class="center">
<?php if (($list['SDL STD Hrs']>0) && (!isset($list['SDL Completed']))){ ?>
<input type="checkbox" name="sdl[]" id="selid<?php echo $i; ?>">
<?php } else if (($list['SDL STD Hrs']>0) && ($list['SDL Completed'] > ' ')){ ?>
<input type="checkbox" name="sdl[]" checked="checked" id="selid<?php echo $i; ?>">
<?php } else { ?>
NR
<?php } ?>
</td>
<td class="center">
<?php if (($list['Mill STD Hrs']>0) && (!isset($list['Mill Completed']))){ ?>
<input type="checkbox" name="mill[]" id="selid<?php echo $i; ?>">
<?php } else if (($list['Mill STD Hrs']>0) && ($list['Mill Completed'] > ' ')){ ?>
<input type="checkbox" name="mill[]" checked="checked" id="selid<?php echo $i; ?>">
<?php } else { ?>
NR
<?php } ?>
</td>
</tr>
<?php ++$i;
} ?>
</tbody>
</table>
<?php } // END if (!isset($_POST['trackingid'])) {
if (isset($_POST['trackingid'])) {
$query = sqlsrv_query($conn, "SELECT * FROM users WHERE id=".$_SESSION['auid']."");
$row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);
$employee_num = $row['Employee Number'];
$size = count($_POST['trackingid']);
for($i=0; $i < $size; $i++){
$trackingid = $_POST['trackingid'][$i];
$query = "UPDATE PD_Tracking SET ";
if(isset($_POST['glass'][$i])){
$query .= "[Glass Completed]='$date_time_entered', [Glass Completed By]='$employee_num', ";
} else {
$query .= "[Glass Completed]= NULL, [Glass Completed By]= NULL, ";
}
if(isset($_POST['sdl'][$i])){
$query .= "[SDL Completed]='$date_time_entered', [SDL Completed By]='$employee_num', ";
} else {
$query .= "[SDL Completed]= NULL, [SDL Completed By]= NULL, ";
}
if(isset($_POST['mill'][$i])){
$query .= "[Mill Completed]='$date_time_entered', [Mill Completed By]='$employee_num' ";
} else {
$query .= "[Mill Completed]= NULL, [Mill Completed By]= NULL ";
}
$query .= "WHERE id='$trackingid'";
$query = sqlsrv_query($conn, $query);
} // END for($i=0; $i < $size; $i++){?>
<SCRIPT LANGUAGE='JavaScript'>
<!-- Begin
window.location = '<?php echo $_SERVER['REQUEST_URI']; ?>&success=edit';
// End -->
</script>
<?php } // END if (isset($_POST['trackingid'])) { ?>

I'm not getting values from session variable set for results

I have created the following pages.
1. questions.php
2. functions.php
3. result.php
i have set the values of session variables on page function.php when the question form on questions.php form is submitted the functions.php code runs and the i have echo the values of session variables on result.php page. but i'm unable to get the session values result.the sessions values are resulting empty .anyone help please.
functions.php
if(isset($_POST['question_form']))
{
global $conn;
if (!isset($_SESSION['result'])) {
$result = 0;
$_SESSION['result'] = 0;
}
if (!isset($_SESSION['attempted'])) {
$attempted = 0;
$_SESSION['attempted'] = 0;
}
$resArray = array();
$resArray['message'] = '';
$resArray['status'] = '';
$no = $_POST['no'];
$postedAnswer = $_POST['answer_'.$no];
$question_id = $_POST['question_id'];
$subject_id = $_POST['subject_id'];
$sql = "SELECT True_answer FROM question WHERE QuestionId = '$question_id' AND SubjectId = '$subject_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$True_answer = $row['True_answer'];
if($postedAnswer === $True_answer)
{
$result = $_SESSION['result'];
$result++;
$_SESSION['result'] = $result;
}
$attempted = $_SESSION['attempted'];
$attempted++;
$_SESSION['attempted'] = $attempted;
$resArray['status'] = true;
//$resArray['q_id'] = $no;
$resArray['message'] = 'Submitted Successfully';
echo json_encode($resArray);
exit();
}
=====questions.php========
<form action="includes/functions.php" id="question_form_<?php echo $j; ?>" >
<div class='container' >
<div class='row'>
<div class='col-lg-12'>
<div class='thumbnail'>
<p id="question_description">Q.<?php echo $i; ?><br><?php echo $row['QuestionDescription']; ?></p>
<div class="questions_options">
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option1']; ?>"><?php echo $row['Option1']; ?></input></label><br>
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option2']; ?>"><?php echo $row['Option2']; ?></input></label><br>
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option3']; ?>"><?php echo $row['Option3']; ?></input></label><br>
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option4']; ?>"><?php echo $row['Option4']; ?></input></label><br><br>
<input type="hidden" name="question_id" value="<?php echo $row['QuestionId'] ?>">
<input type="hidden" name="subject_id" value="<?php echo $row['SubjectId'] ?>">
<input type="hidden" name="question_form" value="question_form">
<input type="hidden" name="no" value="<?php echo $j; ?>">
<button class="btn btn-primary btn-sm" id="btn_submit">Submit<i class="glyphicon glyphicon-arrow-right" >
</i></button>
</div>
</div>
</div>
</div>
</div>
</form>
============result.php===============
<table class="table table-striped table-hover" id="result_table" >
<thead>
<tr>
<th style="text-align: center;">Total Questions</th>
<th style="text-align: center;">Attempted Questions</th>
<th style="text-align: center;">Total Marks</th>
<th style="text-align: center;">Obtained Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><?php echo $number_of_questions;?></td>
<td style="text-align: center;"><?php echo $_SESSION['attempted']; ?></td>
<td style="text-align: center;"><?php if(!isset($_SESSION['result']))
{
echo "empty";
}
else
{
echo $_SESSION['result'];
}
?></td>
<td style="text-align: center;"><?php echo $marks_obtained;?></td>
</tr>
</tbody>
</table>
Please start the session using session_start() function

Store Value from On/Off Button in MySQL Database Using PHP Ajax

I found a tutorial for this with single ID. enter link description here
i have modified as per my knowledge for multiple id, i cannot able to get the id using ajax. i am not good with ajax. I have attached both code. can anyone tell how i can fix it for multiple id
i also attached a screen shot screenshot
index.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
include("connection1.php");
$result = mysql_query("SELECT * FROM mytable ORDER BY id");
?>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<div>
<table id="datatables" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["text"]; ?></td>
<td><script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch<?php echo $row["id"]; ?>').click(function(){
var myonoffswitch<?php echo $row["id"]; ?>=$('#myonoffswitch<?php echo $row["id"]; ?>').val();
if ($("#myonoffswitch<?php echo $row["id"]; ?>:checked").length == 0)
{
var a<?php echo $row["id"]; ?>=myonoffswitch<?php echo $row["id"]; ?>;
}
else
{
var a<?php echo $row["id"]; ?>="off";
}
$.ajax({
type: "POST",
url: "ajax.php",
data: "value="+a<?php echo $row["id"]; ?>,
success: function(html){
$("#display").html(html).show();
}
});
});
});
</script><div class="onoffswitch">
<input type="hidden" value="<?php echo $row["id"]; ?>" name="ids" />
<input type="checkbox" name="onoffswitch<?php echo $row["id"]; ?>" class="onoffswitch-checkbox" id="myonoffswitch<?php echo $row["id"]; ?>"
<?php
$query3=mysql_query("select * from mytable where id=$row[id]");
$query4=mysql_fetch_array($query3);
if($query4['text']=="off")
{
echo "checked";
}
?>>
<label class="onoffswitch-label" for="myonoffswitch<?php echo $row["id"]; ?>">
<div class="onoffswitch-inner"></div>
<div class="onoffswitch-switch"></div>
</label>
</div>
<div id="display"></div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
Ajax.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
if(isset($_POST['value']))
{
$value=$_POST['value'];
$id=$_POST['ids'];
mysql_query("update mytable set text='$value' where id=2");
echo "<h2>You have Chosen the button status as:" .$value."</h2>";
}
?>
For your own sake ;) :
pls organize your code
add an output if something cant be loaded from your db, look therefor in the php example
why the 2. Query, you already loaded all data from 'mytable' with "select *"?
nevertheless here an example based on your code (not tested):
index.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
include("connection1.php");
$result = mysql_query("SELECT * FROM mytable ORDER BY id");
?>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<div>
<table id="datatables" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["text"]; ?></td>
<td>
<div class="onoffswitch">
<input type="hidden" value="<?php echo $row["id"]; ?>" />
<input type="checkbox" class="onoffswitch-checkbox"
<?php
if($row['text']=="off")
{
echo "checked";
}
?>>
<label class="onoffswitch-label" for="myonoffswitch<?php echo $row["id"]; ?>">
<div class="onoffswitch-inner"></div>
<div class="onoffswitch-switch"></div>
</label>
</div>
<div id="display">
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('.onoffswitch').click(function(){
var hiddenValueID = $(this).children(':hidden').val();
if ($(this).children(':checked').length == 0)
{
var valueData = 'on';
}
else
{
var valueData = 'off';
}
$.ajax({
type: "POST",
url: "ajax.php",
data: {value: valueData, id: hiddenValueID} ,
done: function(html){
$("#display").html(html).show();
}
});
});
});
</script>
</div>
ajax.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
if(isset($_POST['value']))
{
$value=$_POST['value'];
$id=$_POST['id'];
mysql_query("update mytable set text='$value' where id=$id");
echo "<h2>You have Chosen the button status as:" .$value."</h2>";
}
?>
You can look in your browsers-console if you get an answer from your ajax-request.

Display only specific array elements in a foreach loop

I have a page that contains an ordering form, on this form it lists the vendor information and then each of the products for the vendor underneath and in front of the product is an input field that allows the user to input the quantity of each product that they want.
Upon submitting the information goes to a confirmation page where I need to be able to show the order information. On the form on the order page, I have a hidden field that contains the vendor id. and the vendor id is put once for each vendor. What I need to be able to do is not only echo out the quantity but also echo out the vendor id specific for each order. My code is below. The first block is the order page and then the block below that will be the confirm page.
As it stands right now underneath every quantity it displays all the vendor ids as opposed to just the one I need.
<?php defined('C5_EXECUTE') or die("Access Denied.");?>
<div class="ccm-ui">
<?php
$db= Loader::db(); //This loads the database helper.
Loader::model('user'); //This loads the user Model.
$user = new User();
$userInfo = UserInfo::getByID($user->getUserID()); //This gets the user info for the current user.
$userCostCenter = $userInfo->getAttribute('cost_center'); //This sets a variable equal to the attribute Cost Center for the current user.
//The if statement below checks if the user is an admin and then displays the info accordingly.
if ($userCostCenter === "Admin") {
?>
<form name="SelectCostCenter" action="/adminorder" method="POST">
<select name="CostCenter">
<option value="unitedilluminating">United Illumination</option>
<option value="clp">CL&P</option>
</select>
<input type="submit" value="Continue">
<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
<?php
} elseif ($userCostCenter === "United Illuminating") {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php
$query = 'SELECT * FROM Vendors WHERE costCenterID = 1';
$productQuery = 'SELECT * FROM Products WHERE costCenterID = 1';
$results = $db->getAll($query);
$productResults = $db->getAll($productQuery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category']; ?></td>
<td><?php echo $vendor['Vendor']; ?></td>
<td><?php echo $vendor['Address']; ?></td>
</tr>
<?php foreach ($productResults as $product) { ?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[]" size="1" /><?php echo $product['Product'];?></span></td>
</tr>
<?php } ?>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
else {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php $query = 'SELECT * FROM Vendors Where costCenterID = 2';
$productquery = 'SELECT * FROM Products WHERE costCenterID = 2';
$results = $db->getAll($query);
$productresults = $db->getAll($productquery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category'];?></td>
<td><?php echo $vendor['Vendor'];?> </td>
<td><?php echo $vendor['Address'];?></td>
</tr>
<?php
foreach ($productresults as $product){
?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[<?php echo $vendor['vendorID']; ?>]" size="1" /><?php echo $product['Product'];?></span></td>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
</tr>
<?php
}
?>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
?>
This is the confirm page below.
<?php defined('C5_EXECUTE') or die("Access Denied.");
$db= Loader::db();
$quantity = $_POST['quantities'];
$vendor = $_POST['vendor'];
$minimumorder = 25;
foreach($quantity as $num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
foreach($vendor as $vendors){
echo "$vendors";
echo "</br>";
}
}
}
?>
I appreciate any help anyone can give. This has had me stumped for a few days actually.
you might want to rearrange your array, and do something like:
$i = 0;
foreach ($productresults as $product) {
echo '<input name="product['.$i.'][quantity]" />';
echo '<input name="product['.$i.'][vendor_id]" value="'.$vendor['vendorID'].'" type="hidden" />';
++$i;
}
The resulting array in $_POST would have the quantities & their vendor separated into their own arrays.
In your code $vendor['vendorID'] seems the key of your $_POST['quantities'] so in your confirm page you could use:
foreach($quantity as $vendorid=>$num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
echo "$vendorid";
}
}

Categories