Get Ajax variable from the PHP foreach loops (part II) - php

Due to dianuj's great help I solved my Ajax looping issue yesterday.
Click here!
The solution helps me to send and get quantity variable (class="qty") every time I change the number in the input area.
Now I want to revise my Ajax and PHP loop a little bit to get the "total" variable (the quantity * the price).
I try to get the "price" variable by puting an "hidden" input area with price values.(please see the following script attached).The script get the variable of quantity (class="qty") and price (class="price") without problem.
However, when I put different quantity the script only picks the very first price and multiplies my changed quantity number.
For example, I have three items in the function with three differnt prices:
1. apple $1 x1
2. orange $10 x3
3. banana $2 x4
the script result will show $1 * (2+3+4) instead the correct $1*2+$10*3+$2*4
(the ajax script still gets the variable of price and quantity without problem).
My Ajax and PHP loops are as follows, it seems they can get and send the qty and price variable without problem (but only the fixed price of the very first item):
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseleave( function() {
//get qty value and price value from the loop
var totalVal =0;
$( ".qty" ).each(function() {
totalVal += ($(this).val()*$(".price").val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: {
//sent the total variable to php script (xml)
total : totalVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<div id="display">
<form action="sessionCartUpdate.php">
<table width="780" border="0" align="center" cellpadding="4" cellspacing="0">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td bgcolor="#CCCCCC" font color="black"><?php echo $_SESSION["psn"][$i];?></td>
<td bgcolor="#CCCCCC"><?php echo $_SESSION["pname"][$i];?></td>
<td bgcolor="#CCCCCC"><?php echo $_SESSION["price"][$i];?></td>
<td bgcolor="#CCCCCC"><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="hidden" class="price" value="<?php echo $_SESSION["price"][$i];?>" >
<td bgcolor="#CCCCCC"><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr><br />
<?php
}
?>
<tr><td colspan="5" align="center">the total:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<div id="result2" class="box" style="height=350px;"></div></td></tr>
</table>
</form>
I also include my php script as follows serving as xml for the ajax script above:
<?php
// XML
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
//get total value ("qty * price") from the ajax
$total = (isset($_POST["total"]) ) ? $_POST["total"] : $_GET["total"];
echo "<?xml version=\"1.0\" ?>";
echo "<caculation>";
echo "<total>" . $total . "</total>";
if ($total==0)
echo "<caution>"."please put number!"."</caution>";
else if ($total<=500)
echo "<caution>"."You should buy more!"."</caution>";
echo "";
echo "</caculation>";
?>
I would be very grateful you could offer invaluble advice to help me fix the above bug!

There is a problem the .each loop is for qty not for the price so it is picking the first price because the loop is for qty not for the price you should do something like this
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseleave( function() {
//get qty value and price value from the loop
var totalVal =0;
$( ".qty" ).each(function(i) {
totalVal += ($(this).val()*$(".price:eq("+i+")").val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: {
//sent the total variable to php script (xml)
total : totalVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
Use the index of .each loop and get the price placed at that index i have used the jquery selector :eq(index here) and i believe there will be price value for each quantity

I haven't confirmed the following code, but it should at least get you on the right track
var totalVal =0;
$('.qty').each(function() {
var price = $(this).closest('tr').find('.price').val();
totalVal += ($(this).val()*price);
});

Related

Get data from php-foreach-loop to ajax

I have searched very long for a solution to this problem but could not find any.
I get data from the database to show some projects on my website. For each project i can click on a pen-symbol to edit the name of the project. I´d like to send the date per ajax request, but always get the data of the first project. If i try for example to edit the name of the second project "test", i get the data of the first project "blubb"
What i have tried:
- Used classes not Id´s
Call Ajax function from PHP foreach with form
- Used $this
Get Ajax variable from the PHP foreach loops
My code lookes like this (simplified):
< script type = "text/javascript" >
$(document).ready(function() {
$(".submit").click(function() {
//here are the problems, i only get the value of the first project
var new_project_name = $('.new_project_name').val();
var old_project_name = $('.old_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
old_project_name: old_project_name,
new_project_name: new_project_name,
name: name
},
}).
done(function(response) {
blabla
});
});
}); < /script>
<?php foreach($db->query('SELECT * FROM portfolio ORDER BY position, id desc') as $row) { $name = $row['name']; ?>
<div class="rename">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Projektname:</td>
</tr>
<tr>
<td>
<input type="text" class="new_project_name" value="<?php echo $name;?>">
</td>
<input type="text" class="old_project_name" value="<?php echo $name;?>" hidden>
</tr>
<tr>
<td>
<input class="submit" type="submit" value="Umbenennen">
</td>
</tr>
</table>
</div>
<?php } ?>
Thank you for any help.
you could pass the id of the project to ajax and update the new value. For that you just need to pass the id of the element.
HTML
<input type="text" class="new_project_name" value="<?php echo $name;?>" rel="<?php echo $id; ?>">
jQuery
$(document).ready(function() {
$(".submit").click(function() {
var parentObj = $(this).closest('.rename');
var id = parentObj.find(' .new_project_name').attr('rel');
var project_name = parentObj.find(' .new_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
project_name : project_name ,
id:id
},
}).
done(function(response) {
blabla
});
});
});
See the Fiddle and check console
http://jsfiddle.net/hoja/2caukhvo/11/

Get Ajax variable from the PHP foreach loops

I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

jQuery clone table row in form does not submit cloned fields

Below is a simplified example that demonstrates the problem I am having. One hundred percent of code is posted below.
Three files work together: testa.php, testb.php, and testc.js. (FWIW, testa.php could function as the index.php, but this is just a demo)
OVERVIEW:
TESTA.PHP
When user clicks anchor tag, sends value to testb.php
Receives ajax response from testb.php into div #reportstable, within FORM structure
Form is submitted to itself, so it prints $_POST data -
TESTB.PHP
receives value from TESTA.PHP, via ajax
outputs table that corresponds to received values
(In this example, I removed how received value is used, but still retained this structure as it affects the jQuery in testc.js)
TESTC.JS
the jQuery that makes it (partially) work
PROBLEM 1: If user adds more than one "document" (i.e. row), only data for the last document appears in the POST data..
PROBLEM2: DocTitle and FileName IDs (dt1, fn1) are not POSTED as they appear in the DOM. In the DOM, their IDs are incremented properly (dt11, dt12, dt13, etc) but when POSTed only one comes through and it has not been incremented. (Use firebug to inspect table elements after adding a couple of documents.
PROBLEM3: First click doesn't "take" when clicking the "choose file" anchor when adding a new document. Any thoughts on this one?
TESTA.PHP
<?php
If (empty($_POST)===false) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
}
?>
<html><body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery-custom-file-input.js"></script>
<script type="text/javascript" src="testc.js"></script>
<br />
Project*:<br />
Click Me
<form action="" method="post">
<div id="reportstable">
</div>
</form>
</body></html>
TESTB.PHP
<?php
$project_id = $_POST['project_id'];
if ($project_id == 5) {
echo '
<table id="DocTable">
<tr>
<th width="150">Document Title</th>
<th width="150">File Name</th>
</tr>
<tr name="tr2" id="tr2" style="display:none;">
<td><input type="text" name="dt1" id="dt1"></td>
<td>
<input type="hidden" name="fn1" id="fn1">
<span id="sp1">choose file<span>
</td>
</tr>
</table>
<br />
add document<br />
<br />
<input type="submit" name="submit" id="submit_it" value="Submit">
';
}
TESTC.JS
$(function(){
var count = 1;
//*******************************************************************
$('#project_pick').click(function(e) {
$(this).hide();
$.ajax({
type: "POST",
url: "testb.php",
data: "project_id=5",
success:function(data){
$('#reportstable').html(data);
}
});
});
//*******************************************************************
$(document).on('click','#ah11',function() {
$(this).file().choose(function(e, input) {
$('#fn11').val(input.val());
$('#sp11').html(input.val());
$('#sp11').css('color','grey');
});
});
//*******************************************************************
$(document).on('click','#ah12',function() {
$(this).file().choose(function(e, input) {
$('#fn12').val(input.val());
$('#sp12').html(input.val());
$('#sp12').css('color','grey');
});
});
//*******************************************************************
$(document).on('click','#ah13',function() {
$(this).file().choose(function(e, input) {
$('#fn13').val(input.val());
$('#sp13').html(input.val());
$('#sp13').css('color','grey');
});
});
//*******************************************************************
$(document).on('click', '#add_row', function() {
$("table#DocTable tr:nth-child(2)")
.clone()
.show()
.find("a, input, span, tr").each(function() {
$(this)
.val('')
.attr('id', function(_, id) {
return id + count;
});
})
.end()
.appendTo("table");
count++;
if (count == 4) {
$('#add_row').prop('disabled', 'disabled');
}
}); //end fn add_row
//*******************************************************************
$(document).on('click', '#submit_it', function() {
alert('This will be submitted now');
});
//*******************************************************************
});
It seems in your javascript that you are changing the values of the id attribute only. However, when you post a form, the id attribute is irrelevant and not posted, you need the name attribute instead.
So where you are changing id's, you really should be changing names (and id's to if you really need them as they need to be unique).
However, a far easier solution would be to use arrays for names, like:
<input type="text" name="dt[]">
If you copy / clone elements with these names and post the form, you will get an array in your $_POST['dt'].

PHP and jQuery update textbox with checkbox value

I have the following functionality I would like to build into a form using jQuery:
I have a list of values:
Invoice No: 110, Amount: 240.00
Invoice No: 111, Amount: 399.00
Invoice No: 112, Amount: 150.00
Next to each row there is a checkbox which is set to checked by default. Right at the bottom there is a textbox with the total 789.00 for the set of data. I would like to update the textbox when one of the checkboxes are de-selected & selected with the total of invoice amounts which checkboxs are checked.
The form will then be submitted to itself with the value of the textbox set.
Any suggestions welcome, as I'm a noob with jQuery.
Just answered similar question here: jQuery - Getting total depending on which checkboxes are selected
put some css class to your invoice total span, ex: <span class="inv-total">120<span>.
then put your checkbox inside of your invoice <div>:
<div>
<input type="checkbox" value="##inv if here ##" />
</div>
and then jQuery of course:
$(document).ready(function() {
$("input[type=checkbox]").click(function(event) {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('#total').val('');
}
else {
$('#total').val('$' + total);
}
});
});
I haven't chanse to test it, but this is the idea.
Live example: http://jsfiddle.net/dH9Eb/2/
$('.checkbox').change(function () {
var text-box-val = $('.textbox').val();
if ($(this).attr("checked")) {
var new-val = $('.textbox').val() + $(this).attr('value');
$('.textbox').val(new-val);
}
else {
var new-val = $('.textbox').val() - $(this).attr('value');
$('.textbox').val(new-val);
}
});
Here is a solution with html table to update amount when you click on a checkbox:
HTML:
<table id="invoices">
<thead>
<tr>
<td>Invoice no</td>
<td>Total</td>
<td>include</td>
</tr>
</thead>
<tbody>
<tr>
<td class="invoiceId">112</td>
<td class="amount">10</td>
<td><input class="amountCheck" type="checkbox" checked="checked"/></td>
</tr>
</tbody>
</table>
jQuery:
$("#invoices .amountCheck").click(function() {
var amount = parseInt($(this).closest("tr").find(".amount").text());
if ($(this).is(":checked")) {
total += amount;
} else {
total -= amount;
}
$("#invoiceTotal").val(total);
});
Don't forget to check if the total is correct on server side.
Working solution : jsFiddle

Ajax to read from form

I'm writing a store system for my game,
it worked quite well until I found out that it only takes the amount of first entered Item.
function pbuy(buyitem) {
var amountc = "amount-"+buyitem,
var amount = $("#"+amountc+"").val();
$.ajax({
type: "POST",
url: "store2.php",
data: "buyitem="+ buyitem+"&amount="+amount,
success: function(resp){
document.getElementById('ajaxDiv').innerHTML = resp;
},
error: function(e){
alert('Error: ' + e);
}
});
}
I'm trying to give it it the Id of the form like so:
function pbuy(buyitem) { var amountc = "amount-"+buyitem, var amount = $("#"+amountc+"").val();
But nothing happens.
The code the creation of the forms is:
<tr>
<td class='items' width='80%' align='center' valign='top'>
<?PHP echo $itemstore->itemname;?>
</td>
<td width="20%">
Price:<?PHP echo $itemstore->newprice;?>
<form method="post">
<input type='text' id='amount-<?PHP echo $row;?>)' />
<input name="itembid" type="button" onclick="pbuy(<?PHP echo $row;?>)" value="Buy" />
</form>
</td>
</tr>
If I hardcode the amount in the ajax function it all runs fine like it should.
You're getting a javascript error before the AJAX-request is being sent since you are defining your amountc and amount variables separated by a comma. Either do
var amountc = "amount-"+buyitem;
var amount = $("#"+amountc+"").val();
semicolon separated, or keep the comma and skip the second var
var amountc = "amount-"+buyitem,
amount = $("#"+amountc+"").val();
Did you checked the response of the AJAX request?

Categories