I have several forms on my page (via a loop), each have it's own submit button.
I want to use AJAX to get and POST the data to a .php. I need to know which form was submitted so I can get the corresponding values.
It's a simple cart application. This form allows a user to change the quantity of the items in the cart before checkout.
You see that there are two "Change Quantity" buttons (sumbit buttons) and these two fields are wrapped in a form tag.
The loop that encloses the form is :
while ($row = $query->fetch_assoc()) {
$item_code = $row['product_id'];
$item_name = $row['name'];
$item_price = $row['price'];
$item_qty = $row['qty'];
print"<tr>
<td>
<img src='http://localhost/store/images/products/$item_code.jpg'>
</td>
<td>$item_code</td>1
<td>$item_name</td>
<td>$$item_price</td>
<td>
<form method='post' action='/store/processing/view_cart.php' class='cart_view_ajax' id='form_id_$item_code'>
<input type='text' maxlength='2' value='$item_qty' id='qty'>
<input type='hidden' value = '$item_code' name='product_id' id='product_id'>
<div><input type='submit' id='submit' value='Change Quantity'></div>
</form>
</td>
<td>x</td>
</tr>";
}
The Question :
How do I know via jQuery that which form was submitted? Help me out...
According the given answers, I've managed to get the Quantity of the submitted form like this by jQuery. Here's the code :
$('form.cart_view_ajax').on('submit', function(e) {
e.preventDefault();
// start working
var form = $(this);
var form_id = form.attr('id');
console.log($('#'+form_id).children().eq(0).val());
return false;
});
You can just use the 'product_id' because it should be unique to each item
<input type='hidden' value = '$item_code' name='product_id' id='product_id'>
Or you can add an unique ID property to the form tag
<form method='post' action='/store/processing/view_cart.php' class='cart_view_ajax' id='item_$item_code'>
$('form#item_3')
You can add an unique id to the row so can manipulate it later on and you can access the form later on.
<tr id="row_$item_code">
$('tr#row_3 form')
You can add 'data' attributes to the form
<form method='post' action='/store/processing/view_cart.php' class='cart_view_ajax' id='item_$item_code' data-form_id="$item_code">
var form_id = $('form#item_3').data('form_id');
Can we see the jQuery code you are currently using?
You may use another hidden input field that contains an identifier for that special form. I think that would be the easiest way to do it.
Related
The following code is in tag_show.php.I have to show all the data from the database and I am trying to edit the database from php code so i form the edit button at the end of all row in html table.
echo"<br><br><br><br>
<table border='6' style= 'background-color: #FFFFE0; color: #761a9b; margin: 2 auto;'>
<thead>
<tr>
<th>tag_title</th>
<th>description</th>
<th>show_in_welcome</th>
<th>status</th>
</tr>
</thread>
<tbody>";
while($row = mysqli_fetch_assoc($get_detail))
{
$_SESSION['tag_title'] =$row['tag_title'];
$_SESSION['description'] =$row['description'];
$_SESSION['show_in_welcome'] =$row['show_in_welcome'];
$_SESSION['status']=$row['status'];
echo
"<tr>
<td>{$_SESSION['tag_title']}</td>
<td>{$_SESSION['description']}</td>
<td>{$_SESSION['show_in_welcome']}</td>
<td>{$row['status']}</td>
<td><form action='edit.php' method='POST'><input type='hidden' name='tag_title' value='".$row["tag_title"]."'/><input type='submit' name='submit-btn' value='edit' /></form></td>
</tr>\n";
}
and the edit.php is
<?php
session_start();
echo"<form action='tag_show.php' method='post'>
<br><br><br>
Tag Title<br><input name='tag_title' type='text' value='{$_SESSION['tag_title']}'><br><br>
Description <br><input name='description' type='text' value='{$_SESSION['description']}'><br><br>
Show in welcome<br><input name='show_in_welcome' type='text' value='{$_SESSION['show_in_welcome']}'><br><br>
Status<br><input name='status' type='text' value='{$_SESSION['status']}'> <br><br>
<input name='submit1' type='submit' value='Update'>
</form>";
?>
but the $_SESSION returns the last row value in HTML table. But i want the receptive row value when i click on edit button.
You don't need a session variable to pass the value to edit.php file.
Hope there is a unique key to identify the record from database. I assume it as recordid. Pass this value to edit.php as a query string
tag_show.php
$output = '';
while($row = mysqli_fetch_assoc($get_detail)){
$output '<tr>
<td>'.$row['tag_title'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['show_in_welcome'].'</td>
<td>'.$row['status'].'</td>
<td>edit</td>
</tr>';
}
In edit.php, you can get the recordid from query string and retrieve the data from database to populate the form
<?php
if($_GET['editid']!=''){
//get record corresponding to the 'editid' from database
//I assume the record is for and store in a variable $editdata
?>
<form action="tag_show.php" method="post">
<br><br><br>
Tag Title<br><input name="tag_title" type="text" value="<?=$editdata['tag_title']?>"><br><br>
Description <br><input name="description" type="text" value="<?=$editdata['description']?>"><br><br>
Show in welcome<br><input name="show_in_welcome" type="text" value="<?=$editdata['show_in_welcome']?>"><br><br>
Status<br><input name="status" type="text" value="<?=$editdata['status']?>"> <br><br>
<input name="submit1" type="submit" value="Update">
</form>
<?php
}
?>
Looks like you are never updating the session data with the information received from the form. You will need something like this somewhere in your code.
$_SESSION['tag_title'] = $_POST['tag_title'];
$_SESSION['description'] = $_POST['description'];
$_SESSION['show_in_welcome'] = $_POST['show_in_welcome'];
$_SESSION['status']= $_POST['status'];
A few things to consider.
Make sure your db info does not overwrite the values after user submits form.
Always sanitize/validate user input before using it (unlike the above code, since it's just an example).
here session make no sense. each time loop runs previous value replaced therefore you are getting last value. Instead of you can use the concept of query strings. Instead of Printing Form print a anchor tag
<a href='file.php?id='.$row["tag_title"]>Edit</a>
Being your tag_title unique.
if(isset($_GET['id))
{
$id = $_['id']
// Your code based on id
}
Now using id run mysql query and select desired data and display in form
Certainly your code will return the last row as the session array overwrites the previous row's value after every iteration.
Make the session array as multi dimensional like $_SESSION[$id]["tag_title"] and then in your edit.php refer to the session array using the id value.
$_SESSION[$id] = array('tag_title' => $row['tag_title'], 'description' => $row['description'], 'show_in_welcome' => $row['show_in_welcome'], 'status' => $row['status'])
Then increment the $id after each iteration.
I have a while loop in PHP that selects data from a database
I want to have a complete button for each row returned which, when pressed will run an SQL Query to change the value of the status column of that particular row
my while loop is:
$stmt = $pdo_conn->prepare("SELECT * from messages where status = :status and (assigned_to = :assigned_to1 OR assigned_to = :assigned_to2) ");
$stmt->execute(array(':status' => '', ':assigned_to1' => $user_result["sequence"], ':assigned_to2' => ''));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$i=0;
if(count($records) > 0) {
echo '<tr>
<td colspan="7">You have '.count($records).' Messages</td>
</tr>';
foreach($records as $Messages) {
$i++;
echo '<tr>
<td>'.AdminNameLookup($Messages["assigned_to"]).'</td>
<td>'.$Messages["caller_company"].'</td>
<td>'.$Messages["caller_telephone"].'</td>
<td>'.$Messages["caller_email"].'</td>
<td>'.$Messages["caller_message"].'</td>
<td><input type="submit" name="CompleteMessages['.$i.']" value="" /></td>
</tr>';
}
}
but I'm not too sure on how to handle the PHP on submit?
Before sending data you need to create html form tag. And also you have pass values using input tag values.
format tag should be like this below code.
<form action="" method="">
<input type="" value="">
<input type="submit" name="CompleteMessages['.$i.']" value="" />
</form>
I would use this instead:
<td><input type="submit" name="CompleteMessages" value="'.$i.'" /></td>
You can then get the id with:
$Id = $_POST['CompleteMessages'];
Personally I'd have $i set to $Messages["message_id"] to you can find what Id you have actually submitted.
You also need to wrap everything in a form tag:
<form action="submit.php" method="POST">
...
</form>
If you only want to change the value of the row where you clicked the submit button,
then you will need a unique key for each record.
Lets assume that the messages table has a MessageID column.
One approach would be to call a javascript function.
Let's say your javascript function was called UpdateColumn(ID,ColName,Index)
Here's what would need to be added to each input button (pseudocode)
onclick="UpdateColumn($Messages['MessageID'],'Status',$i)"
Then your javascript will need to lookup value from input CompleteMessages[Index]
The Javascript could call your request php via ajax ...
update.php?MessageID=MessageID&Column=Status&Value=CompleteMessages[Index].value
And finally your php which handles the submit would take the values
using
$MessageID=$_REQUEST["MessageID"];
$Column=$_REQUEST["Column"];
$Value=$_REQUEST["Value"];
Then you will want to run a sql query which updates your database accordingly.
Is it possible to get the button ID? I have accumulated forms and I wanted to get the button clicked using the unique ID. The following scripts I used:
echo("<table><tr>
<td id=\"i\"><img src='presentations/uploaded_files/$name.png' alt='animal' width='50px' height='50px'/></td>
<td id=\"n\">$name</td>
<td id=\"d\">$dsc</td>
<td id=\"t\">$type</td>
<td id=\"g\">$grade</td>
<td id=\"b\">
<form enctype=\"multipart/form-data\" action=\"admin_update_animal.php\" method=\"POST\"><input type=\"submit\" value=\"Update\" name=\"update\" id=\"$name\"/></form></td>
</tr></table>");
I used the following when any of the button clicked:
if (isset($_POST['update'])) {
$f=trim($_POST['update']);
}
But I wanted to get which button clicked using its unique ID assigned.
I am very glad for a help. Thanks.
You cannot directly read the id of a control because name is passed to the server side script via any methods. You can use hidden input fields whose value can be the id of the button. This lets you know the id of the button in the server side.
This can be done as:-
<script type="text/javascript">
function createField(id)
{
var x = document.getElementById("hide");
var y = "<input type='hidden' name='iddetector' value='"+id+"'/>";
x.innerHTML = y;
return;
}
</script>
//maintain other stuffs here and now
<input type="submit" id="uniqueid" name="submit" value="submit"onClick="createField('uniqueid');return true;"/><br>
<div id="hide"></div>
You can detect the id of the button i the sever side as:-
<?php
$idButton = isset($_POST['iddetector'])?$_POST['iddetector']:NULL;
echo "The id of the button clicked is ".$idButton;
?>
What is passed via POST is the name of the control, not the id. To capture the ID you would be better off using JavaScript before submit.
The point is that you may have multiple controls in different places in the page with the same name (but different IDs) that perform the same task (like submit).
I work with this code:
<form method="get" name="MobileDetails">
<input name="brand" id="brand" value="<?php echo $brand;?>" type="hidden">
<input name="brid" id="brid" value="<?php echo $brandid;?>" type="hidden">
<button type="button" name="submitButton" value="get Details" onclick="getDetails()">
</form>
java script
<script type="text/javascript">
function getDetails(){
var brand = document.getElementById('brand').value;
var brandid = document.getElementById('brid').value;
document.MobileDetails.action = 'details.php?brand='+brand+'&id='+brandid;
document.MobileDetails.submit();
}
</script>
But it does not work in while loop. Whats the problem? My code is given below.
When i click on the button it do not do anything. But the code work great with out while loop given on the top.
<?php
require_once('connection.php');
$SQL= "SELECT*FROM mobile ORDER BY price ASC LIMIT 10";
$result= mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)){
$brand=$db_field['brand'];
$id=$db_field['id'];
$model=$db_field['model'];
echo "<form method='get' name='MobileDetails'>";
echo " <input name='brand' id='brand' value='". $brand ."' type='hidden'>";
echo" <input name='brid' id='brid' value='". $id ."' type='hidden'>";
echo" <input name='mod' id='mod' value='". $model ."' type='hidden'>";
echo" <button type='button' name='submitButton' value='get Details' onclick='getDetails()'/>
</form> ";
echo "CLICK HERE";
}
?>
You're using several times the same id. Ids have to be unique.
Uou are dealing with multiple id's. The job of an ID is to be unique identifier for the element. I suggest just using
<form action="details.php" type="get">
this will do exactly what you are trying to achieve without using the function.
The thing with element ID's is that they need to be unique for the page; however, as you may see, not required for HTML to be displayed. When calling your JS function getDetails(), it grabs the element by ID but when you have multiple ID's in the page, this will fail.
So what can you do? Well, in your loop, you create a new form for each 'brand'. You can pass a reference of the form to the grabdetails and then, by NAME, grab the values from that form.
Rather than using Javascript to generate a link based on given details put in a hidden field, you should just generate the action at the PHP level.
echo "<form method='get' name='MobileDetails' action='details.php?brand=$brand&id=$brandid'>";
But since you do have hidden fields, using just action='details.php' the form will take the user to
details.php?brand={brand}&brid={id}&mod={model}
You should look into POST or making your button into a plain link rather than having a form.
I've used jQuery before to copy billing addresses to shipping addresses, but if I am dynamically generating form rows with various values from PHP, how do I set up the form so that upon a checkmark, a recommended item quantity will be automatically copied just to the quantity of the same item?
Here is the basic version of the billing/shipping copy script.
<script src="../Scripts/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$("input#same").click(function()
{
if ($("input#same").is(':checked'))
{
// Checked, copy values
$("input#qty").val($("input#same").val());
}
else
{
// Clear on uncheck
$("input#quantity").val("");
}
});
});
</script>
And here is the PHP code dynamically gathering items with their suggested quantity.
while( $row = mysql_fetch_array($histresult) )
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td>'.$suggested_quantity.'<input id="same" name="same" type="checkbox" value ="'.$suggested_quantity.'"/> </td>';
echo '<td><input name="qty" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
}
For each item, a suggested wholesale quantity based on a user's favorite items is retrieved from the database. There is also a text field so that they can enter any amount they want before sending it to their cart. But if they check the checkbox, I want it to copy that value to the text field.
No only does this code not seem to do the trick, the difference between this and the billing/shipping copy is that now I'm dealing with a dynamic number of fields. How do I make each individual row achieve this task?
Using jQuery, you would essentially want to grab the suggested value from checkbox and put it in the other form element. Let's say this is your HTML:
<table>
<tr>
<td>
100 <input id="check-1" name="same" type="checkbox" value ="100"/>
<input id="qty-1" name="qty" type="text"size="4" maxlength="4">
</td>
<td>
100 <input id="check-2" name="same" type="checkbox" value ="100"/>
<input id="qty-2" name="qty" type="text"size="4" maxlength="4">
</td>
<td>
100 <input id="check-3" name="same" type="checkbox" value ="100"/>
<input id="qty-3" name="qty" type="text"size="4" maxlength="4">
</td>
</tr>
</table>
And then this would be your javascript/jQuery:
// Bind click event to ALL checkboxes
$("#same-*").live("click", function(e) {
// Only change it if box is checked
if( $(this).is(":checked") )
{
// Get suggested value
suggested_val = $(this).val();
// Place in next element (textbox)
$(this).next().val(suggested_val);
}
)};
I haven't tested this, but this is basically how it would work.
In your PHP, you would want to dynamically make those ID numbers so each row uses a unique ID. This is usually simple enough to match to your database row id.
<td>'.$suggested_quantity.'<input id="same-' . $row->id . '" name="same" type="checkbox" value ="'.$suggested_quantity.'"/> </td>
Change your code this way
<script>
$(document).ready(function(){
$("input.same").click(function()
{
if ($(this).is(':checked'))
{
// Checked, copy values
var temp = $(this).attr("title");
$("input#qty"+temp).val($("input#same"+temp).val());
}
else
{
// Clear on uncheck
$("input#qty"+temp).val("");
}
});
});
</script>
$i=0;
while( $row = mysql_fetch_array($histresult) )
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td>'.$suggested_quantity.'<input class="same" id="same'.$i.'" title="'.$i.'" name="same'.$i.'" type="checkbox" value ="'.$suggested_quantity.'"/> </td>';
echo '<td><input class="qty" name="qty'.$i.'" id="qty'.$i.'" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
$i++;
}
Hope this will helpful to you
Recycling IDs/names amongst several html elements is a bad idea I find.
I think it's best to make them unique.
But anyways, here's a suggestion that won't modify your html structure a lot.
Change the form tag as follows:
<form id="Order">
...
</form>
Change your PHP code as follows (added a label tag to isolate your suggested quantity better in the DOM, got rid of some unnecessary structure for your checkboxes):
while($row=mysql_fetch_array($histresult))
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td><label>'.$suggested_quantity.'<label><input type="checkbox" class="Same"/> </td>';
echo '<td><input name="qty" id="qty_'.$product_id.'" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
}
Finally, here is the jQuery code:
<script src="../Scripts/jquery-1.7.2.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery("form#Order").click(function(Event){ //One event handler for the form, more efficient that way and you need less html structure to keep track of things
var Target = jQuery(Event.target); //This is the html element that got clicked on
if(Target.is("input:checkbox.Same")) //Make sure it's a checkbox that suggests quantity
{
var Text = jQuery(Target.closest('tr').children().get(2)).children(); //Get the parent TR tag, get it's third child (td tag containing the text field), get it's child (the text field)
var Suggested_quantity = Target.prev().html(); //Get the previous sibling which is the label containing the quantity and get it's html content which is the quantity
if(Target.is(":checked"))
{
Text.val(Suggested_quantity);
}
else
{
Text.val("");
}
});
});
</script>
EDIT: Removed some redundant html code. Added a class to isolate the right checkboxes. Added IDs for the text field (forgot).