Cant Run javascript in AJAX file - php

I have a php file and am sending variables from php to ajax file and everything is running great , however when i run javascript in the ajax file
nothing appear like am alerting a msg , nothing is appear , is there any conflict between ajax and javascript ?
This is in the ajax file
<script type="text/javascript" src="js/library.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<?php
session_start();
include("mysqlconnection.php");
if (!isset($_SESSION['username'])) {
echo "<h2 align='center'>Warning: You are not currently signed in </h2>";
die ("<script type = 'text/javascript' language = 'JavaScript'>window.setTimeout(\"location.href='index.php'\", 1000); </script>");
}
$uid=$_SESSION['uid'];
$code = $_GET['user'];
$qty = $_GET['qty'];
$custid = $_GET['custid'];
$warehouseid = $_GET['warehouseid'];
if ($code==''){
$sql1 = "SELECT * FROM itemscopy WHERE uid='$uid'";
$result1=mysql_query($sql1,$con);
if(!$result1)die("Couldn't execute".mysql_error());
?>
<table border="0" width="100%" align="center">
<thead>
<tr>
<th>Code</th>
<th>Code 2</th>
<th>Description</th>
<th>Discount%</th>
<th>Discount Amount</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
<th>After Discount</th>
<th>Warehouse</th>
</tr>
</thead>
<?php
for($counter=0;$row1=mysql_fetch_assoc($result1);$counter++){
$wid=$row1['warehouseid'];
$selwarehouse="SELECT * FROM warehouse
WHERE Id='$wid'";
$runwarehouse=mysql_query($selwarehouse,$con);
if(!$runwarehouse)die("Error");
$rowz=mysql_fetch_assoc($runwarehouse);
if($counter%2==0){
echo ("<tr class='light'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}else{
echo ("<tr class='dark'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}
}
echo "</table>";
?>
</div>
</body>
</html>
<?php
die('');
}
?>
<head>
</head>
<?php
if($warehouseid==''){
die("<h2 align='center'>Please Choose warehouse</h2>");
}
$x=(explode('-',$code));
$code1=$x[0];
$codeid=$x[1];
$code2=$x[2];
$selqty="SELECT * FROM inventory
WHERE itemid='$codeid' AND
warehouseid='$warehouseid'";
$runselqty=mysql_query($selqty,$con);
$rowinventory=mysql_fetch_assoc($runselqty);
if(!$runselqty)die("error");
if(mysql_num_rows($runselqty)==0){
die("<h1 align='center'>This Item Is Not In Your Inventory</h1>");
}
else{
if($rowinventory['qty']<0){
?>
<script type='text/javascript'>
function check(){
var r = confirm("Press a button!");
if(r) {
var urlLink = 'http://www.example.com/warehouse/record.php?codeid=<?php echo $codeid;?>&qty=<?php echo $qty;?>&custid=<?php echo $custid;?>&warehouseid=<?php echo $warehouseid;?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
alert('123');
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
alert('123');
</script>
<?php
// die("<h1 align='center'>The quantity of the item is negative Do you want to continue ?</h1>");
}
else if($rowinventory['qty']-$qty>=0){
// die("<h1 align='center'>The quantity is enough in the inventory You can continue</h1>");
}
else if($rowinventory['qty']-$qty<0){
// die("<h1 align='center'>The available quantity in the inventory is less than the quantity you select</h1>");
}
}
$sqlx = "SELECT * FROM items
WHERE Id='$codeid'";
$resultx=mysql_query($sqlx,$con);
if(!$resultx)die("Couldn't execute".mysql_error());
$row = mysql_fetch_assoc($resultx);
$desc=$row['description'];
$price=$row['price'];
if((!isset($qty))||($qty=='')){
$insert="INSERT INTO itemscopy(code,code2,description,quantity,price,amount,custid,uid,discountper,discountamount,totaldiscount,warehouseid,codeid)Values('$code1','$code2','$desc','1','$price','$price','$custid','$uid','0','0','$price','$warehouseid','$codeid')";
$r=mysql_query($insert,$con);
if(!$r)die("error".mysql_error());
}
else{
$insert="INSERT INTO itemscopy(code,code2,description,quantity,price,amount,custid,uid,discountper,discountamount,totaldiscount,warehouseid,codeid)Values('$code1','$code2','$desc','$qty','$price','$price'*'$qty','$custid','$uid','0','0','$price'*'$qty','$warehouseid','$codeid')";
$r=mysql_query($insert,$con);
if(!$r)die("error".mysql_error());
}
$sql1 = "SELECT * FROM itemscopy WHERE uid='$uid'";
$result1=mysql_query($sql1,$con);
if(!$result1)die("Couldn't execute".mysql_error());
?>
<table border="0" width="100%" align="center">
<thead>
<tr>
<th>Code</th>
<th>Code 2</th>
<th>Description</th>
<th>Discount%</th>
<th>Discount Amount</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
<th>After Discount</th>
<th>Warehouse</th>
</tr>
</thead>
<?php
for($counter=0;$row1=mysql_fetch_assoc($result1);$counter++){
$wid=$row1['warehouseid'];
$selwarehouse="SELECT * FROM warehouse
WHERE Id='$wid'";
$runwarehouse=mysql_query($selwarehouse,$con);
if(!$runwarehouse)die("Error");
$rowz=mysql_fetch_assoc($runwarehouse);
if($counter%2==0){
echo ("<tr class='light'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}else{
echo ("<tr class='dark'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}
}
echo "</table>";
?>
</div>
</body>
</html>
Here is my php code that runs the ajax file where should i put the javascript
<?php
include("header.php");
include("mysqlconnection.php");
if(!isset($_POST['custname'])){
die("<h2 align='center'>YOU ARE NOT ALLOWED TO VISIT THIS PAGE</h2>");
}
?>
<html>
<head>
<script type="text/javascript" src="jquery1.9.1.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquerysearchabledropdown.min.js"></script>
<script>
function showUser(){
var str=document.form.users.value;
var qty=document.form.qty.value;
var custid=document.form.custid.value;
var warehouseid=document.form.warehouse.value;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
alert('123');
}
}
xmlhttp.open("GET","getcode.php?user="+str+"&qty="+qty+"&custid="+custid+"&warehouseid="+warehouseid,true);
xmlhttp.send();
document.form.users.value='';
document.form.users.focus();
}
$(document).ready(function(){
$("#users").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
document.getElementById('goo').click();
}
});
});
$(document).ready(function() {
$("#users2").searchable();
});
function appendSelectOption(str) {
$("#users2").append("<option value=\"" + str + "\">" + str + "</option>");
}
</script>
</head>
<body onload="document.form.users.focus()">
<div id="">
</br></br>
<form name="form" method="post">
<table border="0" align="center">
<tr>
<td align="center"><select id="users2" name="users" width="350" style="width: 230px">
<option value="" selected="selected">Please Select</option>
<?php
$sql1="select code,description,code2,Id from items";
$result1=mysql_query($sql1,$con);
for($counter=0;$row=mysql_fetch_row($result1);$counter++)
print ("<option value = '$row[0]-$row[3]-$row[2]'>$row[0] - $row[1] - $row[2]</option>");
?>
</select>
</td>
<td align="center"><select id="warehouse" name="warehouse" >
<option value="" selected="selected">Please Select</option>
<?php
$sql1="select Id,name from warehouse order by Id Desc";
$result1=mysql_query($sql1,$con);
for($counter=0;$row=mysql_fetch_row($result1);$counter++)
print ("<option value = '$row[0]'>$row[1]</option>");
?>
</select>
</td>
<td>
<input type="text" name="qty" id="qty" size="2"/>
</td>
<td>
<input type="button" name="goo" id="goo" value="GO" onclick="showUser()"/>
</td>
<td>
<input type="hidden" name="custid" id="custid" value="<?php echo $_POST['custname'];?>" size="3"/>
</td>
<td>
<input type="hidden" name="warehouseid" id="warehouseid" value="<?php echo $_POST['warehouse'];?>" size="3"/>
</td>
<td>
<input type="hidden" name="date" id="date" value="<?php echo $_POST['date'];?>"/>
</td>
</tr>
</table>
</form>
</div>
<div id="txtHint"></div>
<script>
$(document).ready(function(){
$('#users').attr("placeholder", "Barcode Search...");
$('#users').focusin(function(){
$(this).attr("placeholder", "");
});
$('#users').focusout(function(){
$(this).attr("placeholder", "Barcode Search...");
});
});
</script>
</body>
</html>

To run a javascript function after your ajax call you should do something like below
$.ajax({
url: "getcode.php?user="+str+"&qty="+qty+"&custid="+custid+"&warehouseid="+warehouseid,
type:"get",
success: function(responseText) {
$("#txtHint").html(responseText);
$("#txtHint").find("script").each(function(i) {
eval($(this).text());
});
}
});
put your javascript function in your success function..
So the function will fire when there is a success ajax call
EDIT
as per your coding you need to do following change in your function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
alert('something') // put some javascript here
}
Let me know if any other help needed

Related

Instant Checkbox update on sql rows with ajax and jquery

Example of what I want:
Hi i want on each row to update instant the checkbox with value 1 when checked and 0 when not checked.
I've make some steps and already taken in a URL via post the values, but I see that updates only on the first row of my table. I think it must have some foreach or loop on ajax to take value to other rows?
This value will export as a URL querystring (ischeck) to an extrnal URL to take import on my function to make the sql query to update the value.
Here is the javascript that for sure want changes about loop that I haven't put on charges.php.
<script>
$(function($) {
var arr = [];
$('input.checkbox').on('change', function() {
var id = "<?php echo $charge['id'] ?>";
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $('[id^="checked-]');
arr.push(check_active);
var url = "ajax_ischeck.php?id=" + id + "&ischeked=" + check_active;
console.log("url", url);
if (this.checked) {
$.ajax({
url: url,
type: "GET",
dataType: 'html',
success: function(response) {
},
});
}
});
});
</script>
Here is the table with the input checkbox sry its little big the checkbox is down to last lines on Charges.php:
<tbody>
<?php foreach ($showcharge as $charge) { ?>
<tr>
<td><?php echo htmlspecialchars($charge['created_at']); ?></td>
<td><?php echo htmlspecialchars($charge['tasks']); ?> </td>
<th width="5%"><?php if (empty($charge['taskcharges'])) {
echo "Free";
} else {
echo htmlspecialchars($charge['taskcharges'] . "\xE2\x82\xAc");
} ?></th>
<th width="5%"><?php
if (empty($charge['payment'])) {
echo htmlspecialchars($charge['payment']);
} else {
echo htmlspecialchars($charge['payment'] . "\xE2\x82\xAc");
}
?>
</th>
<th width="5%" id="balance"><?= htmlspecialchars($charge['balance'] . "\xE2\x82\xAc") ?></th>
<th width="10%"><?php if (($charge['payment_date'] == 0000 - 00 - 00)) {
echo "";
} else {
echo htmlspecialchars($charge['payment_date']);
} ?></th>
<th width="10%"><?php echo htmlspecialchars($charge['admin']); ?></th>
<th width="15%"><?php echo htmlspecialchars($charge['comments']); ?></th>
<td class="mytd">
<form action="" method="POST">
<a href="editcharge.php?id=<?php echo $charge['id'];
echo '&custid=' . $customer['id'] ?>" class="btn btn-info " role=" button " aria-disabled=" true">Edit</a>
</form>
<form id="delete-<?php echo $charge['id'] ?>" onSubmit="return confirm('Are you sure you want to delete?')" method="post">
<input type="hidden" name="id_to_delete" value="<?php echo $charge['id'] ?>" />
<input type="submit" class="btn btn-danger" name=" delete" value="delete" />
</form>
<script>
$("#delete").submit(function() {
return confirm("Are you sure you want to delete?");
});
</script>
</td>
<th width="7%"> <input class="checkbox" type="checkbox" checked value="1" id="checked-1" name="checbox"> <label> Success </label> </input> </th>
</tr>
<?php } ?>
</tbody>
The ajax_ischeck.php that gets data from charges.php post :
<?php include('dataprocess.php'); ?>
<?php include('config/pdo_connect.php'); ?>
<?php
$id = $_GET['id'];
$ischeck = $_GET['ischeck'];
if(isset($_GET["ischeck"])){
Data::ischecked($id, $ischeck);
}
and the sql query:
public static function ischecked ($id, $ischeck)
{
$sql = "UPDATE charges SET
ischecked='$ischeck'
WHERE id=$id";
$statement = conn()->prepare($sql);
$statement->execute();
/* echo $sql;
die(); */
if (!$statement) {
echo "\nPDO::errorInfo():\n";
}
}

Fetch result from Database using Ajax

I want to display info and disable a process button if a certain condition is not met at the point of entering the value(onblur or onkeyup event). I have tried many example but none has given me result. Can someone help me out
The Ajax code:
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select.custid").change(function () {
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url: "process-loan.php",
data: {
custQual: selectedCustomer,
custid: selectedCustId
}
}).done(function (data) {
$("#qualify").html(data);
});
});
});
</script>
Below is the php page
<th>Customer No:</th>
<td>
<select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php while ($rw = mysqli_fetch_array($get)) { ?>
<option value="<?php echo $rw['custid'] ?>"><?php echo $rw['custid'] ?></option>
<?php } ?>
</select>
</td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td id="qualify"> </td>
<td id="qualify"> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
The process-loan.php script that will respond to the ajax call:
<?php
if (isset($_POST["amt"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
$amt = $_GET["amt"];
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if ($amt !== NULL) {
$gets = "SELECT * FROM tab_customer_dailycontribution WHERE custid='" . $custid . "' AND transactionDate BETWEEN '2015-09-01' AND '2015-09-30'";
$get = mysqli_query($connection, $gets);
$sum = 0.00;
while ($row = mysqli_fetch_array($get)) {
$sum += $row['amountContribute'];
}
if ($sum >= $amt) {
//qualify for loan $ enable the Process Button to save
echo "You are Qualify to Apply";
} else {
//disqualify for loan $ disable the process button until condition is meant.
echo "Insufficient Fund: Unqualify to Apply";
}
//end if condition
}
}
?>
this is for demo so i have commented tour mysql related things:first change your keys in process-loan.php.
your view page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#pButton").hide();
$("#amt").on("blur",function(){
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url:"process-loan.php",
data:{custQual:selectedCustomer,custid:selectedCustId},
success:function(data){
var data=JSON.parse(data);
$("#qualify").html(data.msg);//your message
if(data.status == 0){
$("#pButton").show();//showing button if qualified
}else{
$("#pButton").hide();
}
}
});
});
});
</script>
<th>Customer No:</th>
<td><select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php $i =0; while($i <4){?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php $i++;}?></select></td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td ><div id="qualify"></div></td><!-- added div in td to show message it can be outside of your table !-->
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
process-loan.php
<?php
if(isset($_POST["custQual"])){
// include 'includes/session.php';
// include 'includes/db_connection.php';
$amt = $_POST["custQual"];//here use $_POST not $_GET
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if($amt !== NULL){
$sum=100000;//static value for demo
if($sum >= $amt){
//qualify for loan $ enable the Process Button to save
$res["status"]=0;
$res["msg"]="You are Qualify to Apply";
}else{
//disqualify for loan $ disable the process button until condition is meant.
$res["status"]=1;
$res["msg"]= "Insufficient Fund: Unqualify to Apply";
}//end if condition
}else{
$res["status"]=1;
$res["msg"]= "put some amount first";
}
echo json_encode($res);
}

how to update the php variable using jquery variable

Hi I am developing a shopping cart.The products ordered by a customer is shown to him. All the products and their details are stored in a session variable. He can change the quantity of each product, if he wants to.When he changes the quantity of a product,corresponding price changes.This I have done using jquery. Now I need to update the session variable,when he changes the quantity. And I have to display it also.
Here is my code.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
var cart=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
cart +=parseInt(Qty);
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#cart").html(cart);
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
if (confirm("Are you sure to Remove?"))
{
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#cart").html(data.cart);
$("#"+IdForRemove).remove();
});
return false;
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font></b></center>
<?php
}
else
{
?>
<b><font color="#0000A0"> Your Shopping Cart!!</font></b><br><br>
<form name="formview" action="orderform.php" method="post">
<?php $count=0;
?>
<table id="mytable" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="#BDEDFF">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
$cnt=0;
$CartR = $_SESSION['r'];
foreach( $CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?> <tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td>
<input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>">
<?php $tt[]=$ar['Total']; ?>
</tr>
<?php
$cnt++;
endforeach;
?> </table>
<br><br>
<table>
<tr></tr>
<tr><b><font color="B048B5">Grand Total :</font></b> <span id="GrandTotal"></span></tr>
<b><!--<font color="#F6358A">Your Cart:--></font></b><div align="center" id="cart"></div>
<center> <img src="upload/images.jpeg" width="100"></center>
</table>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<!--<b><div id="cart">Your Cart:</div></b> -->
<?php
}
if(!empty($_SESSION['r']))
{ ?>
<input type="submit" name="checkout" value="CheckOut">
<?php } ?>
<b><font color="#7D0541">Back</font></b>
</form>
</body>
Anyone please help me. The change I made using jquery should also change my php variables.
This is my updated sessionupdate.php
<?php session_start();
include('head.php');
$qnty=$_GET['quantity'];
$prce=$_GET['price1'];
$_SESSION['r']=$_GET['id'];
$pid=$_GET['pid'];
foreach ($_SESSION['r'] as $key => $value) {
if($key==$pid){
$_SESSION['r'][$key]['Quantity']= $qnty;
$_SESSION['r'][$key]['Total']= $prce*$qnty;
}
}
here pid is my product_id passed from ajax.Please help me
If you want to update your php variable then you can do so via ajax.Try to do like this:
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
//Call an ajax function here
$.ajax({
type: "GET",
url: "sessionupdate.php",
data: { quantity:Qty,price1:Price,id: <?php echo $_SESSION['r'];?>},
success:function(data){
alert(data);
}
});
});
GrandTotal();
});
sessionupdate.php:
<?php session_start();
include('head.php');
$qnty=$_GET['quantity'];
$prce=$_GET['price1'];
$_SESSION['r']=$_GET['id'];
$pid=$_GET['pid'];
foreach ($_SESSION['r'] as $key => $value) {
if($key==$pid){
$_SESSION['r'][$key]['Quantity']= $qnty;
$_SESSION['r'][$key]['Total']= $prce*$qnty;
echo $_SESSION['r'][$key]['Quantity'];
echo $_SESSION['r'][$key]['Total'];
}
}

Updating session variable based on changes made by jquery

Hi I am developing a shopping cart.The products ordered by a customer is shown to him. All the products and their details are stored in a session variable. He can change the quantity of each product, if he wants to.When he changes the quantity of a product,corresponding price changes.This I have done using jquery. Now I need to update the session variable,when he changes the quantity. And I have to display it also.
Here is my code.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
var cart=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
cart +=parseInt(Qty);
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#cart").html(cart);
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
if (confirm("Are you sure to Remove?"))
{
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#cart").html(data.cart);
$("#"+IdForRemove).remove();
});
return false;
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font></b> </center>
<?php
}
else
{
?>
<b><font color="#0000A0"> Your Shopping Cart!!</font></b><br><br>
<form name="formview" action="orderform.php" method="post">
<?php $count=0;
?>
<table id="mytable" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="#BDEDFF">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
$cnt=0;
$CartR = $_SESSION['r'];
foreach( $CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?> <tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td>
<input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>">
<?php $tt[]=$ar['Total']; ?>
</tr>
<?php
$cnt++;
endforeach;
?> </table>
<br><br>
<table>
<tr></tr>
<tr><b><font color="B048B5">Grand Total :</font></b> <span id="GrandTotal"></span></tr>
<b><!--<font color="#F6358A">Your Cart:--></font></b><div align="center" id="cart"></div>
<center> <img src="upload/images.jpeg" width="100"></center>
</table>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<!--<b><div id="cart">Your Cart:</div></b> -->
<?php
}
if(!empty($_SESSION['r']))
{ ?>
<input type="submit" name="checkout" value="CheckOut">
<?php } ?>
<b><font color="#7D0541">Back</font></b>
</form>
</body>
The change I made using jquery should also change my php variables.
Can you try this.
Added UpdateCart function,
function UpdateCart(Qty, IDCart){
$.ajax({
type: "POST",
url: "UpdateCart.php",
dataType:'json',
data: {id:IDCart, Qty: Qty}
})
.done(function( data ) {
});
return false;
}
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
var IDCart = $("#pid_"+identifier).val();//passing reference value
UpdateCart(Qty, IDCart);//added this for update qty
GrandTotal();
});
GrandTotal();
});
Create one new file : UpdateCart.php
<?php session_start();
if(isset($_POST['id'])){
$toBeUpdate =$_POST['id'];
$CartR =$_SESSION['r'];
$Quantity = $_POST['Qty'];
foreach($CartR as $key=>$Cart){
if($Cart['Id']==$toBeUpdate){
$_SESSION['r'][$key]['Quantity']=$Quantity;
}
}
echo json_encode(array('success'=> true));
}
?>

Populate the third select tag using the value of second select tag which has its values from the database using the first select tag

I used Ajax to populate the values of second select tag but I am not able to populate the third select tag which should appear after the selection of the second select tag. Please suggest what's wrong.
index.php
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getclass(clas) {
var strURL="findbooks.php?clas="+clas;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('booksdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send();
}
}
function getbooks(clas,nme) {
var strURL="findprice.php?clas="+clas+"&nme="+nme;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('pricediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send();
}
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Class</td>
<td width="150"><select name="class" onChange="getclass(this.value)">
<option>select class</option>
<?php
for ($i=1;$i<=10;$i++)
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } ?>
</select></td>
</tr>
<tr style="">
<td>Books</td>
<td ><div id="booksdiv"><select name="Books" >
<option>Select books</option>
</select></div></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="pricediv"><select name="price">
<option>Select price</option>
</select></div></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
findbooks.php
<?php
$class=$_GET['clas'];
include "localhost.php";
$query="SELECT * FROM books WHERE class='".$class."'";
$result=mysql_query($query);
?>
<select name="books" onchange="getbooks(<?php $class; ?>,this.value)" >
<option>Select books</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option><?php echo $row['name'];?></option>
<?php
}
?>
</select>
findprice.php
<?php $class=$_GET['clas'];
$name=$_GET['nme'];
include "localhost.php";
$query="SELECT price FROM books WHERE class='$class' AND name='$name'";
$result=mysql_query($query);
?>
<select name="price">
<option>Select Price</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option><?php $row['price'] ?></option>
<?php } ?>
</select>
The solution is to use Jquery LIVEQUERY. Livequery utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements automatically, even after the page has been loaded!
$(document).ready(function() {
//Populate the third 'select' tag 'onchange' of second 'select' tag.
$('secondSelectTagID').livequery('change', function(){
//Add necessary code to populate third dropdown.
});
});
Note: You have to include both jquery.js and jquery.livequery.js for this approach to work.
In findprice.php
<?php
$class=$_GET['clas'];
include "localhost.php";
$query="SELECT * FROM books WHERE class='".$class."'";
$result=mysql_query($query);
?>
<select name="books" onchange="getbooks(<?php echo $class; ?>,this.value)" ><!--Notice the echo here-->
<option>Select books</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['name'];?>"><?php echo $row['name'];?></option><!--Notice the option value here-->
<?php
}
?>
</select>
And in findprice.php
<?php $class=$_GET['clas'];
$name=$_GET['nme'];
include "localhost.php";
$query="SELECT price FROM books WHERE class='$class' AND name='$name'";
$result=mysql_query($query);
?>
<select name="price" onchange="getbooks(<?php echo $class; ?>,<?php echo $name; ?>,this.value)>
<option>Select Price</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option><?php echo $row['price'] ?></option><!--Notice the echo here-->
<?php } ?>
</select>

Categories