I am creating a application that lets you design a meal and add or remove ingredients. However, the issue I am struggling with is $_POST data. The issue I am running into is I need a button for every $_POST data form submitted.
For example, I can use view meal button to list the ingredients (as seen in the picture), however since this action refreshes the page, the $_POST[meal] data is no longer there. So when I try to remove a ingredient, it can give me the selected ingredient but not the meals name.
What is the right way to get $_POST data? I am having to basically make a new form and button for every submission. Do I need to use some sort of AJAX so it doesn't necessarily refresh the page and I lose that data? Or do I need to use the $_GET method?
<?php
if (isset($_POST['view_meal'])){
$meal = (string)$_POST['meal_names'];
$meal_fk_q = "SELECT item
FROM meal_ingredients
WHERE meal_name='$meal'
ORDER BY item";
$meal_fk_c = $conn->query($meal_fk_q);
$option_string = "";
echo "<div class='view_meal_table_wrapper'>";
while ($row = $meal_fk_c->fetch_assoc()){
$view_ingredient = $row['item'];
echo "<table class='view_meal_table'>
<tr>
<td class='view_meal cell'>$view_ingredient</td>
</tr>
</table>";
$option_string .= "<option>" . $view_ingredient . "</option>";
}
echo "</div>";
echo "<form action='createmeal.php' method='post'>
<select name='remove_ingredients'>
<option disabled selected value> -- Remove Ingredient -- </option>";
echo $option_string;
echo "</select>
<input type='submit' name='remove_ingredient' value='Remove Ingredient'>";
}
if (isset($_POST['remove_ingredient'])){
$ingr = $_POST['remove_ingredients'];
$sql = "DELETE FROM meal_ingredients
WHERE item='$ingr'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
Ajax is the way forwards for you on this one. There are loads more you can add to it to improve, but the basics - using jQuery:
var variable-to-send = 42;
$.ajax ({
type: 'POST',
url: 'php_file_location.php',
data: {name-in-post: variable-to-send, more: more, andmore: andmore}
success: function (response) {
// handle the returned details here
console.log(response);
}
});
Then in php you'd do $data = $_POST ['name-in-post'];
Typed on mobile so apologies if any errors
Related
I am displaying some data from my database, and I wnat to be able to put checkboxes next to each record displayed.
Afther that I want the user to be able to submit their selection and that will then delete the selected records.
I googled a lot of things, but could not make anything work. I'm looking for smething simple.
Here is my code:
<?php
//include('conn.php');
$con=mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
//
?>
<?php
if (!$link = mysql_connect()) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db()) {
echo 'Could not select database';
exit;
}
$villageId = $_GET['village'];
$ID = $_SESSION['ID'];
$sql ="SELECT *
FROM favourites
INNER JOIN attractions ON favourites.AttractionID = attractions.AttractionID
INNER JOIN customer ON favourites.ID = customer.ID
WHERE favourites.ID = '$ID' ";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['Name'] ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Can anyone give me some suggestions?
Thanks.
Simple add checkbox near data output:
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' /> ".$row['Name'];
}
As I understand you need this:
Output some rows data - checkbox
User will select some checkboxes and data, connected with that checkboxes will be deleted from the database.
Delete deleted data from the page.
How to achieve this?
You need html code below to ahieve what you want (+ you need some javascript, I will tell about it later):
<form id='myForm'>
<div id='1'>
<input type='checkbox' name='data[]' value='1' />Row 1</div>
<div id='2'>
<input type='checkbox' name='data[]' value='2' />Row 1</div>
<div id='3'>
<input type='checkbox' name='data[]' value='3' />Row 1</div>
</form>
Look the example of that code + serialize form on link onclick handler here.
Generate same output in PHP:
// execute query
echo "<form id='myForm'>";
while ($row = mysql_fetch_assoc($result)) {
echo "<div id='".$row['id']."'><input type='checkbox' value='".$row['id']."' /> ".$row['Name']." </div>";
}
echo "<a href='#' id='delete'>Delete</a>";
echo "</form>";
So, now we made 1st item of our list and half of 2nd (serialize form).
How to achieve another half of 2nd item. We have to create php script where we will delete rows from the database.
deleteScript.php script:
// connect to the base
foreach($id in $_POST['data']) {
$query = "delete from `favourites` where `id` = ".$id;
// execute your query
}
Script ready. Now you have to send request from our page to this script. Use ajax request for it:
$("#delete").on('click', function () {
var data = $("#myForm").serialize();
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data
});
}
else
{
alert("select some checkboxes");
}
});
This javascript code works with previous html code
Example here.
Now, 1st and 2nd items of our list done.
Let's delete deleted items from our page immidiately (3rd item of todo list):
$("input:checkbox:checked").each(function()
{
var id = $(this).val();
$("div#"+id).remove();
});
You can test this code here
That example was created to show you, that my approach works. But! You have to remove div's only if request had been sent successfully. So you have to edit $.ajax success handler. Check this fiddle for it.
So, now we made all items from our list.
Final example here: http://jsfiddle.net/575VS/18/
You have to copy past it just to your files :)
Hope, this will help.
Note, that you can get ajax-request response.
$.ajax({
//some properties
success: function(data) {
//response will be in data variable
}
});
If you want to redirect page right after deleting selected rows in database use this code:
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data,
success: function() {
window.location.replace("new link here");
}
});
}
Just to expand on Sharikov's answer: You need to place the checkbox in the loop as he described, but if you want to be able to pass that info to another script, that works on the user input you need several more things:
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
}
echo "<input type='submit' value='process'>";
echo "</form>";
Then on receiver.php:
foreach($_POST['checkedBoxes'] as $box){
$id = $box;
//THEN DO SOMETHING TO EACH ID
}
If you also want to see which boxes were unchecked, then things get a little more complicated because POST and GET will only pass the values of checked check-boxes. and there are several ways I can think of to do this. One way would be to pass an array of the all ids displayed via a $_SESSION variable to the next script:
session_start();
$ids = new Array();
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
array_push($ids, $row['id'];
}
$_SESSION['ids'] = $ids;
echo "<input type='submit' value='process'>";
echo "</form>";
And then on receiver.php you can reference that array with $_SESSION['ids'] and compare it to the values that were checked. Just make sure you place session_start(); in your code to be able to see the variable!
Good Luck!
I am trying to use a dynamically generated dropdown list to populate a table. I have a drop down list that is generated from my database (it grabs all the years available for a specific player). I want to be able to select a year from the dropdown and have it update my table. I have the dropdown being generated, but I am not able to get the selected value from the dropdown. I have code below that I found here, but it doesn't seem to work. Here is the code I have so far:
<input name="update" type="submit" value="Update" />
</form>
<p></p>
<form action="player_login.html">
<input type="submit" value="Logout" />
</form>
</div>
<div style="float: left">
<p></p>
<h1>Player Stats</h1>
<table width="300" border="1" cellpadding="2" cellspacing="2">
<?php
// get "id" field from player table
$login_id = $_COOKIE["DB"];
$id = "select id from player where login_id='$login_id';";
$result1=mysql_query($id) or die('Select1 Query failed: ' . mysql_error());
$row = mysql_fetch_array($result1);
// create a dropdown from stats table in db
echo "--Select Year--";
$years_query = "select year from stats where player_id='$row[id]';";
$years = mysql_query($years_query, $connect);
// fill array with db info
$var = array();
while ($row2 = mysql_fetch_array($years))
{
$var[] = $row2['year'];
}
// create dropdown
echo'<select name="years" id="years">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select>';
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query) or die('Select2 Query failed: ' . mysql_error());
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
// create table with results
echo "<tr>";
echo "<td>Year</td>";
$j=1;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Total Points</td>";
$j=2;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>PPG</td>";
$j=3;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
?>
</table>
</div>
I see that you use $_POST and since form is not submitted and thus data of $_POST is not set. Best available option I have used to catch the event and send the AJAX Query fetch results and update it.
I have done this with the help of J Query as under
$('#years').change(function() {
$.ajax({
//request of AJAX
type : 'POST',
url : 'players_data.php',
dataType : 'json',
data: {
//Data with $_POST request
years : $('#years').val();
},
success: function(data){
//Things to be done with returned data
}
}};
Create a new file players_data.php and there you write the code for fetching data from the db as:
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query);
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
$return['year']=$line;
echo json_encode($return);
I see that you are using $_POST, and why do you don't use a form?
//This is for get the form
echo '<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>';
//create a form
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
// create dropdown; onchange will send the form when selected index changes...
echo '<select name="years" id="years" onchange="get_form(this).submit(); return false;">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select></form>';
And that's all! :D
I'm seeing too that you are using an unique form for update all the page... It's isn't work, because you only have a submit button and no more element in the form, please read that: http://www.w3schools.com/tags/tag_form.asp
From your code i can see that u want to get the value from the select box and immediately populate the table and display the results..use jquery to get the value of selected object and assign the javascript variable to a php variable. and insert into the db..
<script type="text/javascript">
$( "#years" ).change(function() {
var value=document.getElementById("years").value;
alert(value);
</script>
assign the variable to php and execute you php query.
<?php
$data = "<script>document.write(value)</script>";
//execute your query here..
?>
Also have a look at ajax..it does that so well...
Following on from my question yesterday, I now have the code below somewhat successfully working. It allows me to change the first form item and submits it to 'process.php' in the background and turns the field green. However the trigger only works on the first form item, in this case "cstate". It doesn't trigger when "clocation" is changed. If you change clocation and then cstate then both form submit fine so it's simply that the .change function isn't triggering when clocation is changed. I'm not good enough at JS (total JS noob) to know why it isn't working so I'd appreciate any help you can give me.
Thanks!
$sql = "select * from `$table1`";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$carid = $row["car_id"];
$carnum = $row["carnum"];
$carlocation = $row["carlocation"];
$carstate = $row["carstate"];
$formname = "#form".$carid;
print '<script type="text/javascript">';
print " var cnum;";
print " cnum = '$formname',";
print "
$('form').change(function()
{
console.log(cnum);
$.ajax({
type: 'post',
url: 'process.php',
data: $(this).serialize(),
success: function() {
}
});
return false;
});
</script>";
echo "<table>";
echo "<tr id='$carid'>";
echo "<td>$carnum</td>";
echo "<td><form action='' method='post' id='form$carid'>";
echo "<select id='popup' name='cstate'>";
echo "<option value='In-Service-Bay'>In Service Bay</option>";
echo "<option value='Awaiting-Service'>Awaiting Service</option>";
echo "<option value='Service-Complete'>Service Complete</option>";
echo "</select></td>";
echo "<select id='popup' name='clocation'>";
echo "<option value='Carpark-1'>Carpark-1</option>";
echo "<option value='Carpark-2'>Carpark-2</option>";
echo "<option value='Carpark-3'>Carpark-3</option>";
echo "</select></td>";
echo "</form></tr>";
}
echo "</table>";
Use .on() and wrap code inside document.ready.
$(document).ready(function(){
$('form').on('submit',function()
{
//code here
});
});
also put this code outside the while loop. Also form does not have change event try using .submit()
Solved it by using a separate form for each input selection. Works brilliantly now.
Thanks to all those that tried to help.
Adam
I am trying to create a calender with a checkbox for each date. When a user clicks the submit button, I want to get those selected dates inserted into the database and those which are not selected would be deleted from the database if those already exist before. I have created a index.php page where I wrote the following code to generate dates:
index.php:
<form name="form1" method="post" action="show.php">
<?php
$year="2011";
$month="8";
$d=cal_days_in_month(CAL_GREGORIAN,1,2011);
$i=1;
while($i<=$d)
{
?>
<input type="checkbox" name="date[]" value="<? echo " $year-$month- " . $i . ""."<br>"; ?>">
<? echo " $year-$month- " . $i . ""."<br>"; ?>
<?
$i++;
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
show.php:
<?
mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
$media_array = $_POST['date'];
foreach ($media_array as $one_media)
{
$source .= $one_media.", ";
}
$media = substr($source, 0, -2);
$query = "INSERT INTO table1 (id,media) VALUES('', '$media')";
$result = mysql_query($query); }
?>
And then I created page another page named show.php where I tried to write codes for inserting information, but I failed.
Would you please kindly help me to do this? I have tried my best but I couldn't make it happened. Thanks in advance.
The easiest way would be to make use of Ajax (going to use the JQuery library to make it a bit easier). So every time a checkbox changes values an Ajax request is triggered to updateDatabase.php and it either deletes or inserts a record.
So if you are showing your checkboxes on the page do:
<script>
$(document).ready(function() {
//Every time a checkbox changes (gets ticked or unticked) send n Ajax request
//to updateDatabase.php containing its value and a BOOLEAN checked/unchecked
$('input[type="checkbox"]').change(function() {
var checked = $(this).is(':checked');
$.ajax({
url: "updateDatabase.php",
type: "POST",
data: {value : $(this).val(),
checked : checked },
dataType: "html",
async:false,
success: function(msg) {
//Show the answer from the file in an alertbox.
//Use this to debug your code. Leave it out afterwards.
alert(msg);
}
});
});
});
</script>
So every time a checkbox is checked or unchecked it sends its value and the "checked" boolean value to updateDatabase.php.
In this file you can do something similar to:
updateDatabase.php
<?php
//Get POST variables
$value = mysql_real_escape_string($_POST['value']);
$checked = $_POST['checked'];
//If the checkbox was checked, INSERT its value into the database
//else you remove it.
if ($checked == true) {
$query = "INSERT INTO table (value) VALUES ('" . $value . "')";
}
else {
$query = "DELETE FROM table WHERE value = '" . $value . "'";
}
mysql_query($query);
?>
EDIT: Added the code to process the data after you click SUBMIT
If you do not want to do this on the flow
If you want to update your database when the user clicks SUBMIT, you simply submit the form to show.php.
show.php
<?php
$dates = $_POST["date"];
echo "Dates chosen: " . count($dates) . "<br /><br />";
if (count($dates)>0) {
echo "You picked the following dates:<br />";
}
for ($i=0; $i<count($dates); $i++) {
echo ($i+1) . ") " . $dates[$i] . "<br />";
mysql_query("INSERT INTO table (value) VALUES ('" . mysql_real_escape_string($dates[$i]) . "')");
}
?>
Hope this helps you!
(I did not test this code so I'm sorry if there are some minor errors in there still. But I'm sure you catch the drift!)
i have this scenario in my program, i'm printing a list of check boxes to my main page using below codes
<form action="two.php" method="post">
<div id="option_box" style="width: 250px; height: 400px; overflow: scroll;">
<?php
$sql = "SELECT * FROM gene_names ORDER BY name";
$result = $db->query($sql);
$counter = 0;
echo "<table border=\"0\">";
while ($row = $result->fetch()) {
$output[] = "<tr>";
$output[] = "<td>";
$output[] = "<input type=\"checkbox\" value=\"".$row['name']."\" name=\"things[]\" id=\"ran\"/>";
$output[] = " ";
$output[] = $row['name'];
$output[] = "</td>";
$output[] = "</tr>";
$counter++;
}
echo join('',$output);
echo "</table>";
?>
</div>
<input type="submit" value="See Interactions" name="see" id="see"/>
</form>
after that i'm using the below code to get the process done using jquery ajax
$('#see').click(function(eve){
eve.preventDefault();
$.post('two.php', function(data) {
$('#results_of_interactions').html(data);
});
});
but i need to get the selected check box values inside my two.php(the files handling the processes of the above form) file in order to execute a sql query, but when i use this jquery approach the check box variables are not available at my two.php file, so my query is not properly executed and i can't get the results, how can i correct this issue?please suggest some thing to do, a modification to this or another approach?
regards,
Rangana
That's because you have to manually prepare the data and send it along with your post request, it does not submit the form, it submits whatever you manually tell it to submit to two.php
$('#see').click(function(eve){
eve.preventDefault();
//serialize form data to be sent with request
var data = $('form').serialize();
//send request with 'data'
$.post('two.php', data, function(data) {
$('#results_of_interactions').html(data);
},'json');
});