Fetch result from Database using Ajax - php

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);
}

Related

How to get values from foreach loop of php in jquery

I'm Working on a plugin in Wordpress in which i'm storing values in new table which is created on plugin activation its working perfectly.
Now I fetched values from table like following
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id ?>">
</td>
<td width="26%">
<textarea rows="3" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
after fetching the data I display the values in form of listing.
Now I want to update values of input fields and textarea through ajax for which I wrote following code
add_action('wp_ajax_ajc_update_values', 'ajc_update_value');
add_action('wp_ajax_nopriv_ajc_update_values', 'ajc_update_value');
add_action("admin_head", "ajc_input_ajax");
function ajc_input_ajax()
{
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id = jQuery('.ajc_field_id').val();
var update_link = jQuery('.img_link').val();
var update_desc = jQuery('.img_description').val();
var update_title = jQuery('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
<?php
}
//Updating values in database
function ajc_update_value()
{
$id = $_POST['ajc_id'];
$link = $_POST['ajc_update_link'];
$desc = $_POST['ajc_update_desc'];
$title = $_POST['ajc_update_title'];
global $wpdb;
$wpdb->update(
'wp_ajc_images',
array(
'ajc_img_title' => $title,
'ajc_img_description' => $desc,
'ajc_img_link' => $link
),
array('ajc_img_id' => $id)
)
die();
return true;
}
When I click on first item's update button it alerts me right id eg. (12) and update it, but when I click on rest of the item's update button it alerts me first item's id (12) and data is not updated.
Hope you'll understand my question.
Try this code. add id to every fields like id="img_link_<?php echo $row->ajc_img_id; ?>"
HTML code
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" id="img_link_<?php echo $row->ajc_img_id; ?>" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id; ?>">
</td>
<td width="26%">
<textarea rows="3" id="img_description_<?php echo $row->ajc_img_id; ?>" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" id="img_title_<?php echo $row->ajc_img_id; ?>" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" data-id="<?php echo $row->ajc_img_id; ?>" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
Script code
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id =jQuery(this).attr('data-id');
var update_link = jQuery('#img_link'+id).val();
var update_desc = jQuery('#img_description'+id).val();
var update_title = jQuery('#img_title'+id).val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
You're displaying values based on a class name and there could be many elements with same class name. What you need to do is target specific <tr> and get values from that <tr> only.
So your jQuery code should look like this:
jQuery("#update").click(function () {
var id = $(this).parents('tr').find('.ajc_field_id').val();
var update_link = $(this).parents('tr').find('.img_link').val();
var update_desc = $(this).parents('tr').find('.img_description').val();
var update_title = $(this).parents('tr').find('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
You just have to add $(this).parents('tr').find before selecting values from every element.

multiple submit on same page with php ajax

<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.

Cant Run javascript in AJAX file

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

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));
}
?>

Categories