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');
});
Related
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
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
SCROLL TO FIND WORKING CODE
I am working on a AJAX editing platform, and I am having trouble with setting up the text field for editing.
My code so far:
The Javascript below handles the initial submission:
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function edit()
{
var doc_id = document.getElementById("doc_id").value;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
document.getElementById('content').innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
The SQL below handles the initial select query and display of that information:
$query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured`, ';
$query.= 'FROM `primary_physicians` AS pp ';
$query.= 'ORDER BY pp.`physician_id` ';
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
echo "<td><div id='content'><input id='doc_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' value='Edit' onclick='edit();'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
</html>
And the 'ajax.php' file handles the request when the user clicks the 'Edit' button within the 'content' div.
$client_id = $_GET['doc_id'];
$client_query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured` ';
$client_query.= 'FROM `primary_physicians` AS pp WHERE pp.`physician_id`=' . $client_id . '';
$client_result = mysql_unbuffered_query( $client_query );
while ($client_row = mysql_fetch_assoc($client_result))
{
echo "<input type='text' value='$client_row[physician_first_name]' />";
}
What shows is below:
Initial page load:
Pressing the 'edit' button (any of the available buttons, not just the one associated with the client/ID):
Pressing any edit button shows client ID #2 within client ID #1's table row (not in the row with client ID #2):
I'm guessing I have to set up something within the content div and somehow associate it with the 'edit()' function, however I can't figure out how to do that without setting the script within the while loop (which I really don't want to do).
WORKING CODE BELOW
Javascript (initial submission and display):
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function hello(e)
{
/* this was once document.getElementById("doc_id").value;*/
var doc_id = e.currentTarget.id;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
/*this was without the '+doc_id' document.getElementById('content').innerHTML = ajax.responseText; */
document.getElementById('content'+doc_id).innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
PHP/MySQL:
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
//note change to the 'content' div (addition of $physician_id to make it truly unique; this ties into the javascript above.
echo "<td><div id='content$physician_id'>";
//note changes to input id and button id, as well as the 'onclick' function.
echo "<input id='doc_id_$physician_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' id='$physician_id' value='Edit' onclick='hello(event);'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
No changes to or initial MySQL query or to ajax.php
There is a problem with the elements' ids. Remeber that the id attribute should be unique inside a document. You are using the same id for numerous elements:
td><div id='content'><input id='doc_id' type='hidden' ...
inside a loop.
Then you use the Javascript document.getElementById('doc_id'). JS supposes there is only one element with this id on the page so it will always return the first element it finds.
EDIT:
You will have to also change your JS function to retrieve the proper value:
for the edit buttons use: onclick="edit(event)"
And then in the JS:
function edit(e) {
buttonId = e.currentTarget.id;
//use the button id to find the proper value
}
Of course you will have to set the id on the "edit" buttons and have it correspond with id of you inputs. E.g. use $i for the button id and doc_id_$i for the input id.
I also recommend having a look at jQuery, as it will help facilitate many of the things you're trying to achieve here.