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!
Related
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>
I have a table with dynamically created rows ('s) - in each is a set of inputs, one of which is an autocomplete input field where the user can search for an item and is given a list of choices, when they select one, the details of their ITEM are populated in all the remaining fields and an image that corresponds to their choice is called from the Database.
Here's my DB call Query:
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' LIMIT 5");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['product_name'] = $row['name_en-GB'];
$row_array['category'] = $row ['meta_keyword_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array );
}
mysql_close($conn);
echo json_encode($return_arr);
In my JQuery all I have to do is place this:
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
So it will put the Image into the div ID : prodImage.
I have tried IF Statements:
if ($('#prodImage').length)
{
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
}
else {
$('#prodImage').remove();
}
And ...
if (!$('#imgLoads').length)
{
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
}
else if($('#imgLoads').length){
$('#prodImage').remove();
}
And a whole bunch of variations and replaceWith() statements, but to no avail.
You can check out the live interface here :
http://cardoso.co.za/index.php/login-shop
Username: stackUser
Password: demo
What happens, at best, is the images bunch up one under the other ...
Any help is appreciated. I have also tried the following post, but it didn't work :(
Change image src with jQuery autocomplete
In Response to RST's piece of code, here is how I have tried to implement it so that it only changes the image in the exact TR where the autocomlete ifield is changed:
$(this).closest('#product_name').blur(function(){
$('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
});
This is how I solved the issue:
$(this).closest('tr').find('#product_name').blur(function(){
$(this).closest('tr').find('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
$(this).closest('tr').find ('.imgLoads').attr('style','border-radius:8px;-webkit-border-radius:8px;-moz-border-radius:8px;border:solid 1px #CF3;');
});
In your HTML set the image tag already
<div id="prodImage">
<img class="imgLoads" src="">
</div>
jQuery
$('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
This code should go in a function, something like:
$('#some-element-id').change(function(){
$('#prodImage img.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
)};
So it will adjust when selections are made.
Solved by using this code, after tweaking a lot of things, thanks again RST!
$(this).closest('tr').find('#product_name').blur(function(){
$(this).closest('tr').find('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
$(this).closest('tr').find ('.imgLoads').attr('style','border-radius:8px;-webkit-border-radius:8px;-moz-border-radius:8px;border:solid 1px #CF3;');
});
I am passing data using J-Query and AJAX to res.php page:-
attempt.php (my main page from where the res.php is called)
$.ajax(
{
url: "res.php",
type: "POST",
data: data,
success: function (data)
{
var build_id='build_';
build_id += i;
alert(build_id);
$('#npc').append(data);
$('#build_id').attr('disabled','true');
var total = $("#build_id");
alert(total);
}
});
In the res.php page I am using the passed data to generate the query and retrieve data from the database and calculated the total value and display the total in a text box.
res.php
$i = mysql_real_escape_string($_POST['i']);
$query = "select * from ";
$query = $query . $building;
$query = $query . " where lvl=" . $level;
$query = $query . ";";
$result = mysql_query($query) or die('Error in Child Table!');
echo $i;
while( $data = mysql_fetch_assoc($result))
{
$total_res = $data['lumber'] + $data['clay'] + $data['iron'] + $data['crop'];
echo '<tr><td>'. $building. '</td><td>'. $level. '</td><td><input type="text" style="width:70px" id="build_' . $i . '" value="' . $total_res . '"></td></tr>';
}
I am using id="build_' . $i . '" to auto increment the id of the text box. Till here everything goes fine.
Back to the attampt.php page,
when I try to access the data from the text box i am unable to access it.
The code that I'm using to access the data is:-
var build_id='build_';
build_id += i;
$('#build_id').attr('disabled','true');
var total = $("#build_id");
alert(total);
the alert function at the end of the code gives the following output:-
[object Object]
I am trying to append a list of text boxes with some values to a table and then calculate the sum of all the values in the text boxes.
Please help.
$('#build_id') should be $('#'+build_id) and to calculate the total of all the values, you should put var total=0; outside your callback function, and the function should contain
total += $('#'+build_id).val();
Another problem is that each row of the table has the same id="build_$i", but IDs have to be unique.
And do you really intend to display $i at the beginning of the table, without it being in a table row?
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
});