How to get string value from js function in td table? - javascript

I'm working with PHP and Javascript. I return arrayList from PHP file to PHP web page; in the PHP web page I want to display array list in a table, but one of the fields "state" can be "Success or Rejected", if success, the td table shows span bootstrap icon, else, also. I using Javascript function for return span icon, but it can't read param "state" to invoke function.
My js file:
function getStateIcon(strState) {
var strHtml = '';
if (strState === "Success") {
strHtml = '<span class="label label-success">' + strState +'</span>';
} else if (strState === "Rejected") {
strHtml = '<span class="label label-warning">' + strState + '</span>';
}
return strHtml;
}
And my php web page:
<table>
//headers.....
//body
<?php
include_once '../../Model/RequestDto.php';
$list = new ArrayObject();
if (isset($_SESSION["list"]) == null) {
echo 'not found results';
} else {
$list = $_SESSION["list"];
foreach ($list as $val) {
?>
<tr>
<td><?php echo $val->getID?></td>
<td><?php echo $val->getDate()?></td>
<td><script type="text/javascript">getStateIcon(<?php echo $val->getState()?>);</script></td> //here i want pass parameter state to the js function for return span icon and draw td, but this show empty
</tr>
<?php
}
}
?>
</tbody>
</table>

You're returning the string to the caller of the function instead of writing it to the innerHTML of the td.
Actually you can easily do that with CSS by styling the td's. But if you want to use JavaScript, you need to manipulate the DOM innerHTML of the td's. For example:
<td class="Success"><td>
And, add the onload attribute to the body.
<body onload="buildIcons()">
Then the JavaScript can be written like this.
function buildIcons() {
var tds = document.getElementsByClassName('Success');
for (var i = tds.length - 1; i >= 0; --i) {
var td = tds[i];
td.innerHTML = "echo the img here";
}
}
It can be done easier with CSS.
.Success {
background: 'path to bg image';
}

You have a misconception about how JavaScript interacts with the page. Your PHP uses echo to write values into the page before it gets sent to the client.
Your JavaScript function gets called and returns a string, but this string is never written to the page.
You could fix your JavaScript to manipulate the page DOM, but this is unnecessary. At the time the php is executed, it knows the state and can easily write the span tags into the page with the echo method.
You don't need the JavaScript at all.

Related

why html tags does't work and show as string value?

I want to ask advice from you guys since I have a problem of showing html tags within table structure.
Actually, I want to show is "link".
To be clear I will explain you more details.
I am making auto generated table structure view with the help of javascript and jquery that shows data from database and want to show these data as table structure which also include the link that allows user to edit the data. That's it.
See the below image:
As you can see, links are showing as normal characters.
So anyone who knows the answer please advice me.
Below is the code:
//php
$sql = "SELECT * FROM v_category";
$dbaction = new db_action($sql,'G');
$result = $dbaction->db_process();
$dataRows = "Category Name|Remark|Edit|";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ctgr_id = $row["ctgr_id"];
$ctgr_name = $row["ctgr_name"];
$remark = $row["remk"];
$link = "<a href='?cv=ms-category&mode=2&id=$ctgr_id'>link</a>";
$dataRows = $dataRows . "**row**" . $ctgr_name . "|";
$dataRows = $dataRows . $remark . "|";
$dataRows = $dataRows . $link;
}
} else {
echo "0 results";
}
echo '<div id="draw-grid" class="tbl-responsive" style="overflow-x:auto;"><script>DrawTable("draw-grid","'.$dataRows.'");</script></div>';
//javascript
function DrawTable(Container,dataRows)
{
dataRows = dataRows.split(ROW_SPLITTER);
var tTable=$('<table>');
//draw the table header
tTable.append(drawHeader(dataRows[0]));
//draw the table body
tTable.append(drawBody(dataRows));
//add table to wrapper container first and then add into the parent container
$('<div>').append(tTable)
.appendTo($('#'+Container));
return;
}
function drawHeader(headerRow)
{
var headerRowColumns = headerRow.split("|");
var tblRow=$('<tr>');
headerRowColumns.forEach(function(element,index) {
$('<th>')
.text(element)
.appendTo(tblRow);
});
return $('<thead>').append(tblRow);
}
function drawBody(objRows)
{
var tBody=$('<tbody>');
objRows.forEach(
function(objRow,index)
{
if(index!=0)
{
tBody.append(drawBodyRow(objRow,index));
}
});
return tBody;
}
function drawBodyRow(bodyRow,rowIndex)
{
var bodyRowColumns = bodyRow.split("|");
var tRow=$('<tr>');
bodyRowColumns.forEach(function(element,columnIndex)
{
$('<td>').text(element).appendTo(tRow);
});
return tRow;
}
$('<td>').text(element).appendTo(tRow);
In this line and others like it, you're setting the inner text of the matched elements to be a value.
This is actually a good thing in almost all cases. You don't want to be interjecting arbitrary HTML into a context where a text value is intended. Otherwise, you open up yourself to potential security issues, or at least, invalid HTML.
What you should be doing instead, if you really intend to inject HTML, is to append those elements to this one.
Your code has other problems too...
$link = "<a href='?cv=ms-category&mode=2&id=$ctgr_id'>link</a>";
In this line, you're interpolating arbitrary data into a URL and into HTML, with nothing being escaped. Use http_build_query() to escape the data for the query string. Then, be sure to use htmlspecialchars() for any arbitrary data injected into HTML to ensure it's escaped for that context.

How to delete row in html based on cell value

I am trying to delete a row based on a table's cell value.
In my HTML page I have a simple search function. It would send the values in the text box to the database through ajax then PHP and then PHP would create a table dynamically based on what is in the database.
I have tried to check a the cell in the table for a specific value so that if it is true then the current row would be removed, the function name is checkMatch(). However it doesn't work.
This is the button in the HTML, the rest of the HTML is just a text box and drop down box:
<input type="button" id="device_search" value="Search" onclick="searchDevice(); checkMatch();"></input>
This is the function in the external JavaScript file:
function checkMatch()
{
var row = document.getElementById("thisRow");
var cell = Row.getElementById("match");
if(cell[0].innerText = "0%")
{
row.deleteRow(this);
}
}
And here's the creating of table in the PHP:
if($num_row)
{
echo "<table id=\"myTable\" border=\"1\">";
echo "<tr>
<th>Board ID</th>
<th>Tester Name</th>
<th>Board Name</th>
<th>Current Slot</th>
<th>Log Created</th>
<th>Required Slot</th>
<th>Match</th>
</tr>";
while($row = mysql_fetch_assoc($result))
{
$board_id = $row['board_id'];
$tester_name = $row['tester_name'];
$board_name = $row['board_name'];
$config = $row['config'];
$log_created = $row['log_created'];
$req_config = $row['configuration'];
$exploded = explode(",", $req_config);
$count = count($exploded);
$j = 0;
foreach($exploded as $value)
{
$number = strlen($value);
$arr = str_split($value, $number);
if(in_array($config, $arr))
{
$j += 1;
$j /= ($count / 100);
echo $j;
}
else
{
}
}
echo "<tr id = \"thisRow\">
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$req_config</td>
<td id = \"match\">$j%</td>
</tr>";
}
echo "</table>";
}
The column that I'm checking on is the last column which is the Match column. My idea is to remove that current row whenever the cell value of Match is 0%. I can't seem to find what's wrong with my codes, I'm not really good at manipulating DOM elements either so there must be some mistake. Any help on this? Or are there others ways, through PHP etc?
Note: I am not trying to delete the row from database. I just want to remove the row whenever Match is 0%.
EDIT, codes for searchDevice() in external js file:
function searchDevice()
{
var device_name = $("#device_name").val();
var tester_type = $("#tester_type").val();
var page = "database.php";
if(device_name==""||tester_type=="")
{
alert("Please do not leave any blanks.");
}
else
{
$.post(page, {
device_name : device_name,
tester_type : tester_type,
action : "search"
}, function(data) {
$("div#display_board").html(data);
checkMatch();
});
}
}
Currently my table does display with all the right values, but it doesn't remove the rows with 0%.
checkMatch() should be called at ajax success callback
id should be unique with in HTML document
PHP
// use `class` instead of `id`
echo "<tr class=\"thisRow\">
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$req_config</td>
<td class=\"match\">$j%</td>
</tr>";
Javascript
function checkMatch()
{
$("#myTable tr.thisRow").each(function() {
var thisRow = $(this);
var match = thisRow.find(".match");
// note the `==` operator
if(match.text() == "0%") {
thisRow.hide();
// OR thisRow.remove();
}
});
}

javascript call inside php where loop not working and breaks query

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

Ignoring links, checkboxes.. in an editable html field using jquery

Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out

loading php page only when the div containing him becomes visible

i make some sort of a shopping cart that when i press on a table line it suppose to open some details about the item, for this purpose i used a div which is at height 0 and hidden at first which contains the details, the problem is that i think that the browser will load the the info pages regardless of if the line was pressed or not. is there any way to make the browser load the page only when his DIV is visible?
$int = 0;
echo "<table class=\"result_table\" id=\"result_table\">";
foreach($types as $data){
echo "<tr onClick=\"present(".$int.");\" >";
echo "<td align=\"right\">";
echo $data['number'];
echo "</td>";
echo "<td align=\"right\">";
echo $data['item_name'];
echo "</td>";
echo "<td align=\"right\">";
echo $data['amount'];
echo "</td>";
echo "<td align=\"right\">";
echo "17";
echo "</td></tr>";
echo "<tr class=\"info_row\"><td colspan=\"4\"><div id=\"div_num_".$int."\" style=\"height:0px\">
<object type=\"text/html\" data=\"page.php\" style=\"width:100%; height:100%; margin:0%;\">
</div></td></tr>";
$int++;
}
echo "</form></table>";
the css for the row
.info_row{
visibility:hidden;
}
the JS:
function present(item_id){
var div = document.getElementById("div_num_"+item_id);
if(div.style.visibility=="visible"){
div.style.visibility = 'hidden';
div.style.height= '0';
} else {
div.style.visibility = 'visible';
div.style.height= "200px";
}
}
as you can see all the info loads with the page but are invisible.
other good ways of tackling this problem will be appritiated especially if it does not include jquery because i am not really strong in it.
thanks in advance.
Firstly, if there isn't much info to load, preloading the data is probably more sensible anyway. Users want a responsive UI, even if it means a few extra milliseconds of initial download time for data they'll never see.
But, if you insist on loading the data separately, you could use an xmlhttprequest to load a representation of the data (such as in JSON), and use a templating solution to output the result into the info div.
The page that might generate the JSON representation of the data might look something like this:
<?php
$result = array();
// ... Code that defines type ... //
$int = 0;
foreach($types as $data){
$result[] = array(
"int" => $int,
"number" => $data["number"],
"item_name" => $data["item_name"],
"amount" => $data["amount"]
);
$int++;
}
echo json_encode($result);
?>
So, when a user clicks a link, the above page would load in an xmlhttprequest. You could then parse the result with JSON.parse(req.responseText), and apply an HTML template to the result (check out the above link, plus this one, for more info on how to do that).
Again, you're probably fine just loading all the data in one go. Extra HTTP headers actually make pages take longer to completely load.
You can use an ajax call:
with javascript
<script type="text/javascript">
function loadInfoRow()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
//Use the response text to add the extra row
}
}
xmlhttp.open("GET","info.txt",true);
xmlhttp.send();
}
</script>
with jquery
$.ajax({
url: "info.txt",
context: document.body,
success: function(text){
//where text will be the text returned by the ajax call
$(".result_table).append(text);
}
});

Categories