Assume I have some data from the database and store in a array, which like this:
$testArray = array(
array('0', 'name1', 'status1'),
array('1', 'name2', 'status2')
);
and I can print the content of the array as a html table, like this way:
Id name status
0 name1 status1
1 name2 status2
I want to use a 'status' dropdown list at the end of each row to change the status of each entry, and update into the database table. My questions are:
How do I get the row id of each row(the 'Id' column) when I select a option of the drodown list?
How to pass these info to the backend inorder to update the database table? I guess it should use some javascript. And below is the code:
<?php
$testArray = array(
array('0', 'name1', 'status1'),
array('1', 'name2', 'status2')
);
?>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>Id</td>
<td>name</td>
<td>status</td>
</tr>
<?php
for ($i = 0; $i < count($testArray); $i++){
echo '<tr>';
for ($j = 0; $j < count($testArray[$i]); $j++){
echo '<td>';
echo $testArray[$i][$j];
echo '</td>';
}
echo '<td>';
echo '<select>';
echo "'<option value='0'>status1</option>";
echo "'<option value='1'>status2</option>";
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
</table>
</body>
</html>
Thanks for help!
You Could:
Give each of your select's an id that correspond to the row of data.
On change(jQuery), Get the value of the select, and use the jquery ajax call to send the rowID, and the 'StatusValue' to the handling page.
Show an status message on return of data.
http://api.jquery.com/jQuery.ajax/
--Building the Select
<?php
for ($i = 0; $i < count($testArray); $i++){
echo '<tr>';
for ($j = 0; $j < count($testArray[$i]); $j++){
echo '<td>';
echo $testArray[$i][$j];
echo '</td>';
}
echo '<td>';
**echo '<select id="' + $testArray[$i][0] + '">';**
echo "'<option value='0'>status1</option>";
echo "'<option value='1'>status2</option>";
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
--The jQuery (you will need the jquery file, download from jquery.com)
$(document).ready(function(){
$('select').change(function () {
var rowIdVal = $(this).attr('id'); // the id of the select (your rowID)
var statusVal = $(this).val(); // the value of the select
// post id to the server using ajax (you can use jQuery ajax request)
////I would check if the values are valid and not null...
$.ajax({
type: "POST",
url: "YOURHANDLERFILE.php",
data: {status: statusVal, rowId: rowIdVal},
success: function(d){
//show a status message
}
});
});
});
You can:
Store your row id in the hidden field in the first column and the get using jQuery
Store as id attribute and then using jQuery get the value
(I think the best one) store the id in id attribute in the your select control and then get value on selected index change using jQuery
in html you will have:
<select id="1">
in javascript:
$('select').change(function () {
var id = $(this).attr('id');
// post id to the server using ajax (you can use jQuery ajax request)
});
I would do something like
$('#yourTableId').find('select').change(function() { //bind a change event to the selects
$(this).closest('tr') //this way you get the tr element of the row you changed the select value
.find('td:first') //or .find('td').first(). This will give you the td element for the Id column
.val(); //The actual value of the td Id element
});
Related
I am new here and newbie learner. I've checked some similar questions like this but could not get them to work.
What I am trying to achieve is, querying my database, retrieve list of accounts, then jquery function sends a query to ajaxtest2.php file for each of the account to retrieve account information and shows it in a html table.
Main problem is, table is populating with information of the last account in the database instead of all accounts.
I am getting this output at the moment:
`3459 1459 3459 1459`
Your help will be much appreciated.
Thank yoU :)
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
?>
<script type="text/javascript">
$(document).ready(function() {
$(window).load(function() {
var numValue = <?php echo $var; ?>;
$.getJSON("ajaxtest2.php", {number: numValue}, function(data){
var trHTML = '';
$.each(data, function () {
trHTML += '<td>' + data.bal + '</td><td>' + data.eq + '</td>';
});
$('#location').append(trHTML);
});
}); `
});
</script>
<table id="location" border='1'>
</table>
<?php
}
The below is the response from ajaxtest2.php
echo json_encode(array("bal" => "$balance", "eq" => "$equity"));
?>
Make sure that you have table rows when you generate the cells.
trHTML += '<tr><td>' + data.bal + '</td><td>' + data.eq + '</td></tr>';
Else your cells will always append to the right of the previous cell without changing rows
Also, the your code could all be done using PHP only (no js)
Here's how:
<?php
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
?>
<table id="location" border='1'>
<?php
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
//your ajaxtest2.php functionnalities go here
//let's say $accBalance and $accEquity contain the information you wanted about that specific row
echo '<tr><td>'.$accBalance.'</td><td>'.$accEquity.'</td></tr>';
}
?>
</table>
And there you have your populated table using database values without using JS.
Hoped it helped!
I need help for display selecting data value from database into a specific position in a html table.
I have made the code for displaying it but it will display the data in index 0 on the html table.
Anyone know how to make the data will displaying at index 1 on the html table?
I've try to change the index but it failed to displaying it.
Here my code:
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
var tr = "<tr>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
This is the {data} that i use. i use php function for the data
<?php
$con=mysqli_connect("localhost","root","","silo");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Data for Titik1
$query = mysqli_query($con,"SELECT * FROM temp2");
$rows = array();
while($tmp= mysqli_fetch_array($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($con);
?>
can you please more explain what shape you mold with html Table. basically table row always append with general indexing. if you need a black row before your data row so kindly append a blank row in your html table.
If you want the index number of the row to show on the html table, then you need to add a new column before all other columns. This new column will show the serial number of the row. For example before this line:
tr += "<td>"+list[i]["tanggal"]+"</td>";
Add this line:
tr += "<td>"+ (i+1) +"</td>";
So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>
EDIT QUESTION:
In my WHILE loop, it creates an readonly input text box, and the values are whatever records it pulls from my Database. After each text box, there is an add button, which is suppose to append the value of the text box beside the button, to another div on my page. The only value being added is the first record. I know why, I just can't fix. Any ideas?
$query = "SELECT `$posResults` FROM test.departments ";
$result = mysql_query($query);
if ($result) {
//output results from database
echo 'Software';
while($row = mysql_fetch_array($result))
{
echo '<tr>';
echo '<td><input type="text" id="rSoft" size="50" name="reqSoft" value="'.$row[0].'" readonly/> <button id="toForm" value="Add" >Add</button>';
echo '</td>';
echo '</tr>';
}
echo "<script type='text/javascript'>$(document).ready(function(){ $('button#toForm').click(function(){ var req = document.getElementById('rSoft').value; $('<tr><td>' + req + '</td></tr>').appendTo('#empInfo');}); });</script>";
}
Here is an image. When I Hit Add, I want the value to go to the div. Right now, only the first value is being appended.
Found out the answer that covers everything:
On my main page:
$query = "SELECT `$posResults` FROM test.departments ";
$result = mysql_query($query);
if ($result) {
//output results from database
echo 'Software';
echo '<table>';
$i = 0;
while($row = mysql_fetch_array($result))
{
echo '<tr><td><input type="text" id="rSoft'.$i.'" value="'.$row[0].'" name="reqSoft" readonly/>';
echo '<button id="toForm'.$i.'" data="rSoft'.$i.'" >Add</button>';
$i++;
}
echo '</table>';
}
On my JS page:
/*Add software to form*/
$(document).ready(function(){
$('button').on('click' , function(){
var inputID = $(this).attr('data');
var theValue = $('#' + inputID).val();
$('#empInfo').append('<tr><td>' + theValue + '</td></tr>')
});
This will append the data of the input box to where I need it to go. Thank you OIS and Kristen Jukowski for getting me started on the resolution!
});
The IDs of your inputs need to be unique. You can pass the values, though, as an array if you change the ID to something like this:
echo '<td><input type="text" id="reqSoft[]" size="50" name="reqSoft[]" value="'.$row[0].'" readonly/> <button id="toForm" value="Add" >Add</button>';
Your passed values will be available as an array in $_POST['reqSoft']. (First textbox value would be $_POST['reqSoft'][0], etc.)
Similar question/answer here: Dynamically create unique ID for an array of input fields using Javascript
Is it possible to automatically get first item from drop down list to the input on page load? For example, the drop down list have 2 options: happy& sad. When the page loads, I want happy to be in the input on page load. So far, I got an empty input where the user need to select the option on the drop down list.
Jquery code:
<script type="text/javascript">
$(document).ready(function() {
$("#username_select").change(function() {
$("#username_custom").val($(this).val());
});
});
</script>
username_custom id:
<input id="username_custom" name="custom" value="
<?php
if(isset($_POST['getusername'])) {
$getusername = $_POST['getusername'];
echo "".$getusername."";
}
if(empty($_POST['username'])) {
echo "".$row['username']."";
}
?>
">
username_select id:
<select id="username_select" name="getusername">
<?php
$username = $_SESSION['username'];
$result = mysql_query("SELECT username FROM account WHERE websiteusername='".$username."'");
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row['username']."'>".$row['username']."</option>";
}
?>
</select>
To show the selected value of select in input
$("#YourInputId").val($("#username_custom").val());
To set the first option text of select
$("#YourInputId").val($("#username_custom option:eq(0)").text());
To change the textbox value on change of select
$(document).ready(function() {
$("#username_select").change(function() {
$("#username_custom").val($(this).val());
$("#YourInputId").val($("#username_custom").val());
});
});
In this line
echo "<option value='".$row['username']."'>".$row['username']."</option>";
you can add SELECTED to the option you want to get selected. You can use a variable in the while loop to find out which item you are at and get that item selected;
For ex.
$ctr = 0;
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row['username']."'" . ( $ctr == 1 ? "selected" : "" ) . ">".$row['username']."</option>";
$ctr++
}
Hope this helps.
Cheers
In this case you can also call change event of drop down.
$("#username_select").change();