Get Ajax variable from the PHP foreach loops - php

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.

Related

How to display the results from a separate PHP file in an HTML page?

I need to display the sum in the HTML form page itself. A part of the code is given below in my PHP file:
<?php
while($row = mysqli_fetch_array($search_result)):?>
<?php
$sum=$sum+$row['value'];
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['value'];?></td>
</tr>
<?php endwhile;?>
In my HTML form I have a total button. When I click that, I need to display the sum value. How can I do that?
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button">Total</button><br><br>
</form>
As I assume that you want to show total, if it is correct then follow below method
$sum = 0;
while($row = mysqli_fetch_array($search_result)):?>
$sum+= $row['value'];
<?php endwhile;?>
echo $sum;
or
if you want to show result without reloading the page. you have to code in ajax request.
We use ajax in html page to access the content from the php page :
HTML:
<html>
<script src="jquery.min.js"></script> // script download
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button" id="total">Total</button><br><br>
Your sum:<span id="sum"></span>
</form>
</html>
<script>
$( "#total" ).click(function() {
$.ajax({
url : "phptest.php",
type: "POST",
success: function(data)
{
$('#sum').html(data);
}
});
});
</script>
PHP: here your php code
<?php
echo "10";
?>
You need to use PHP SESSIONs, and play with the information you're sending in the POST request. Basically, both buttons will need to be of type submit so that they both send the request to the process (process.php). Then you can use sessions to set your results.
Do it in this manner:
index.php
<?php session_start(); ?>
<form action="process.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button name="total_btn" type="submit">Total</button>
</form>
<div id="results">
<?= (!empty($_SESSION["table"])) ? $_SESSION["table"] : "" ?>
<br>
<?= (!empty($_SESSION["sum"])) ? "Sum: " . $_SESSION["sum"] : "" ?>
</div>
<?php
session_destroy();
process.php
<?php
session_start();
$sum = 0;
$table = "<table>";
while ($row = mysqli_fetch_array($search_result)) {
$sum += $row['value'];
$table .= "<tr>
<td>{$row['id']}</td>
<td>{$row['time']}</td>
<td>{$row['value']}</td>
</tr>";
}
$table .= "</table>";
if (isset($_POST['total_btn'])) {
$_SESSION["sum"] = $sum;
}
$_SESSION["table"] = $table;
header('Location: index.php');
if i understood your problem correctly, then u need Ajax call. GET or POST based on your preferences.on that your HTML code will be separate from php code basically php code will respond to Ajax call and give you out put.
Modified code- Test.html
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button" id="gettotal">Total</button><br><br>
</form>
<script>
$("#gettotal").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',//based on your choice or requirement
url: 'calculate.php',
success: function(response) {
//here u decide where to show output value
alert(response);
},
error: function(result) {
alert('error');
}
});
});
</script>
calculate.php
<?php
$sum = 0;
while($row = mysqli_fetch_array($search_result))
{
//calculate your total and send back as JSON obj.
$sum=$sum+$row['value'];
}
echo json_encode($sum);
?>

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

jquery $.post fails to send data on second request

I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.
you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.

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/

Jquery Form Submit Keeps Refreshing

For some reason this form keeps refreshing the page and I have no idea why as I have another form on the page with a different id but same script and it doesn't refresh. I have tried using preventDefault(); as well but it doesnt work either. Can someone please tell me where I have gone wrong in this form or script?
Thanks
Top of page
<script type="text/javascript" src="../JS/jquery.js"></script>
<script type="text/javascript" src="../JS/jquery-ui.js"></script>
<script type="text/javascript" src="../JS/member_info.js"></script>
The Form
<form id="central">
<table width="40%" class="search">
<tr>
<td width="39%" align="left"><p><b>Inception Date:</b></p><input size="10" maxlength="10" id="creddate" type="text" value="<?php echo $creddate; ?>" /></td>
<td width="41%" align="left"><p><b>Surety:</b></p><input size="15" maxlength="15" id="surety" type="text" value="<?php echo $surety; ?>" /></td>
<td width="20%" align="left"><p><b>Credit Limit:</b></p><input size="15" maxlength="15" id="creditlimit" type="text" value="<?php echo $credlimit; ?>" /></td>
</tr>
</table>
<br />
<table style="margin:0 auto">
<tr>
<td><input type="hidden" id="code" size="12" readonly="true" value="<?php echo $code; ?>" /></input></td>
<td><input type="submit" value=" Save " /></input></td>
<td><p align="center" id="central_status"></p></td>
</tr>
</table>
</form>
The Script - Linked from member_info.js
$(document).ready(function(){
$("form#central").submit(function() {
var code = $('#code').val();
var inception = $('#creddate').val();
var surety = $('#surety').val();
var credit = $('#creditlimit').val();
$.ajax ({
type: "POST",
url: '../members/edit_central.php',
data: {code: code, creddate: creddate, surety: surety, creditlimit: creditlimit},
success: function(data) {
$('#central_status').html(data);
}
});
return false;
});
});
Make sure you preventDefault() immediately after the form is submitted. Don't do anything else before you do that (like calling Ajax).
E.g.:
$("form#central").submit(function(e) {
e.preventDefault();
// Your other long running (possibly async)
// operations here
}
Also, make sure you are not adding the form dynamically to the page. If you do so, you need to attach the submit event live. Like so:
$(document).on('submit', 'form#central', function(e){
// same as above
});
use input type button insted of submit
<input type="button" value=" Save " name="saveButton" id="saveButton" />
in simple return false at the end of the click event handling do the trick for example :
$('form input[type="submit"]').click(function() {
....
return false;
})

Categories