Getting a record row in php using javascript - php

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!

I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});

This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}

Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.

I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

Related

Separating <td> in a <tr> using jquery when pulled from an onclick event

Before we start I am fairly new to jquery and do not know most of the functions and capability, so I do not know if there is an easy trick to do this that I am missing.
I am having an issue where I am using a search function to display a table of results using Jquery, ajax and PHP. Once the results table is displayed from the search, I have a clickable link on the final row of the table. This link should get the data from the row you clicked on and set it to a $_SESSION in PHP. I can get the correct data fine, I just cannot separate out each <td> field individually. I wish to do this by adding in a comma or a symbol that I could use to identify each separate field once in PHP. This is an issue as I wish to put it into an array to auto-fill some input on the next page that you get redirected too. Can anyone help or point me in the right direction for this.
Jquery + ajax
$('#resultviews').on("click",".buttonaslink",function(){
var tabler = $(this).closest("tr").text();
tabler = ('tabler=' + tabler);
alert(tabler);
$.ajax({
type: "POST",
url: "rowsession.php",
data: tabler,
cache: false,
success: function(html){
$('#resultviews').html(html).show();
}});
return false;
});
PHP how results are displayed in the table from first ajax POST
while ($row = mysqli_fetch_array($view)){
$id = $row['companyId'];
$company = $customers[$id];
$company = ucwords($company);
echo "<tr><td class='tabled'>". $row['ip']."</td><td class='table'>". $row['Subnet']."</td><td class='table'>".$row['hostName']."</td><td class='table'>". $row['owner']."</td><td class='table'>". $company ."</td><td class='table'>".$row['siteName']."</td><td class='table'><button id='rowbtn' class='buttonaslink'>Edit</button> / <button id='rowdel' class='btnaslink'>del</button><tr>";
}
You can try this approach:
var tabler = $(this).closest("tr").find("td")
.map(function() {
return $(this).text();
})
.get()
.join(",");
It takes a value from every td element of the row and joins them with a comma. If you need to remove a trailing comma, you can use this code:
if(tabler.length) {
tabler = tabler.substring(0, tabler.length - 1);
}

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

Using one <form>'s selection to feed into another <form>?

From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())

How to get value of dynamic id in an html loop with javascript?

I am creating a drag and drop system using redips javascript.
This is my script using html and php to generate the data
<div id="base">
<table>
<tbody>
<?php
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus" value="'.$row['description'].'"></div></td></tr>';
}
?>
</tbody>
</table>
</div>
This is the fragment of my javascript file.
var redips_init;
redips_init = function () {
// reference to the REDIPS.drag
var rd = REDIPS.drag;
// initialization
rd.init();
rd.drop_option = 'shift';
rd.animation_shift = true;
rd.myhandler_dropped = function () {
alert($('#bus').val());
}
};
I am not good with php but what i usually do in jsp is create a local index variable and append it to each of the ID attribute in the loop.
So your code would look something like this
<?php
$index=0;
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus'.$index++.'" value="'.$row['description'].'"></div></td></tr>';
}
?>
In javascript, your dragAndDrop event should return an index location by which u can get appropriate value.
Now you can use this dynamic ID in your JavaScript to do whatever you want to do.
REDIPS.drag contains save_content() method to scan all DIV elements in a table and to return the result as Query string or JSON object. Input parameters are table id and type of returned result (default is query string). If this is not good enough, you can search for save_content() source and make customization. Method is simple and it uses several loops to scan table content.
On the other hand, if you need to know ID of dropped DIV element that can be written inside myhandler_dropped event hander. Here is code snippet:
rd.myhandler_dropped = function () {
// define DIV id
var id = rd.obj.id;
// write DIV id to the console
console.log(id)
};
Hope this answer will be helpful.

Calling a JavaScript function based on PHP, PHP in JavaScript

I have this JavaScript code that creates a table, and puts in the rows and columns.
I want to call this function, based upon some data in a database. So the amount of rows is based upon the amount of data in the database.
My data in my database is a markscheme, I want the the table to fill depending upon the amount of questions are in the database
I have tried and here is my code:
hasLoaded = true;//page loaded set to true
<?php
$query = "SELECT maxMark, criteria FROM mark ";
$result = mysql_query($query);
while ($result != null)
{
addRow();//add row with everything in
}
The correct answer is json_encode your data from PHP and store it in a JavaScript variable like this.
<?php
// populate the php rows array
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows = array_push($rows, $row);
}
?>
<script>
// populate the javascript rows array
var rows = <?php echo json_encode($rows); ?>;
for (var = 0; i < rows.length; i++) {
addRow(rows[i]);
}
</script>
I would not recommend Jamund's solution, as it would require either inline javascript, or parsing your javascript files through PHP. I would recommend using an Ajax post in your javascript function to fetch the data from your server, and then populating from there.
$(document).ready(function(){
$.ajax({
type: "POST",
url: "yourscript.php",
data:{param1: 'yourParam'},
success: PopulateTable
});
});
functionPopulateTable(data, status)
{
// Build Table with data
}
http://api.jquery.com/jQuery.ajax/ is a good place to start if you are using jQuery on your page.

Categories