how to get the td id in JavaScript - javascript

<table class="table" style="margin-bottom:0px!important">
<b>
<? if(!empty($channelBase['rep_ids']))
{
$s_id=$channelBase['id'];
$i=0;
$temp='';
$reps_channl=explode(",",$channelBase['rep_ids']);
foreach($reps_channl as $k)
{
$added_reps = $rep_names[$k];
if($i==0){
$temp.='<tr style="border-top:none;">';
}
$temp.="<td id='".$s_id."_".$k."' class='repclicked' style='border-top:none;'>$added_reps <a href='#' class='btn btn-xs btn-icon btn-circle ' onclick='delete_repid($k,$s_id);'><i class='fa fa-close'></i></a>
</td>";
$i++;
if($i==5)
{
$temp.='</tr>';
$i=0;
}
}
echo $temp;
}
?>
</b>
</table>
Here I have a td id with a number value. here I am getting confusion on how to get the td id in javascript. can anyone please help me.

Here is how you can get Ids of td inside table
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
console.log(cell.id)
}
}
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td id="id_1">col1 Val1</td>
<td id="id_2">col2 Val2</td>
</tr>
<tr>
<td id="id_3">col1 Val3</td>
<td id="id_4">col2 Val4</td>
</tr>
</table>
</div>

Try this,
"<td id='".$s_id."_".$k."' onclick='alert(this.id);'></td>"

You are trying to mix PHP and javascript, which you can not do. Everything in PHP is separate from javascript and the two do not have access to identifiers from each other.
The reason is this:
PHP code is completely run BEFORE the page is loaded. Once the page is loaded completely in PHP, it is then sent to the browser where the javascript acts upon whatever the result of the PHP code was.
Try this:
on a page enter:
<pre>
<?php
$a = "1";
$b = "2";
print_r($a);
print_r($b);
?>
</pre>
Now load the page and right click on the page and go to "inspect " or "view source"
you will see that the source of the page has no php code and is only
<pre>12</pre>
This is because all PHP code is processed BEFORE the page is loaded, whereas javascript is processed AFTER the page is sent to the browser.
You have to do everything involving PHP Ids first and completely separate from javascript, and likewise javascript must be completely separate from PHP.
For your case you must make a separate request in order to modify an array in PHP and then either reload the page or use AJAX to load the updated data.
The type of action you are trying to accomplish is impossible the way you are trying to do it.

Related

Can't getElementById (HTMLDOM object is supposedly null). Where am I messing up?

So I've been stuck on this for a bit...
I have an HTML page with a div element and an inline frame (iframe):
<!DOCTYPE html>
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/GLS_DBSearchProject/resources/css/GLS_DBSearchMainStyle.css"></head>
<div id="DebugOutput">DEBUG-OUTPUT</div>
<body align="center">
<div class="PWContainer"><iframe class="ProgramWindow" src="index.php"></iframe></div>
</body>
<?php
The div is simply there as a box that I made for testing as I get comfortable with JavaScript. The iframe houses a separate .php page "index.php". The HTML for "index.php" is entirely generated by the functions in this php code:
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawAdvancedSearchBar();
}
//Override this function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
echo '
<!----Header-HTML--------------------->
<div align="center">
<table width="980" height="207" border="0">
<tr>
<td width="411"><img src="resources/logo.png" alt="" width="491" height="145" align="middle" /></td>
<td width="411"><img src="resources/Logo2.png" width="462" height="171" alt="Logo" /></td>
</tr>
</table>
</div>
<!------------------------------------>
<body>
<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js>
</script>
</body>
';
echo '$AppInstanceData: ' . '<br>';
echo '--CurrentDBSet_Str: ' . $this->ParentAppInstance->CurrentDBSet_Str;
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet(this.ownerDocument)" name="DBSetList" form="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSets_Arr as $DBSet){
if($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
In the DrawDBSetDropdown() function of the UserInterface class, I am drawing a selection box with variable options. Whenever the user changes the state of this selector, I'm calling the SwitchDatabaseSet() javascript function with the HTML DOM object of "index.php".
Up to this point, everything seems to work fine. Here's where things get weird:
function JSTEST(){
window.alert("JS Called Successfully!!");
}
function SwitchDatabaseSet(MainPageDoc){
window.alert(null === MainPageDoc);//1.
window.alert(MainPageDoc.domain);//2.
MainPageDoc.getElementById("DebugOutput").innerHTML = "Test";//3.
}
Result: false. MainPageDoc is not null.
Result: localhost. As expected the page is running on localhost. Notably, MainPageDoc != null.
Suddenly MainPageDoc supposedly equals null; as I get the following Error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
*document.getElementById() produces an identical result.
I'm trying to change the text of the DebugOutput <div>, but it's not working because of the issue above.
In 1. and 2. both indicate that MainPageDoc isn't null, so why am I getting the error at 3. ? What am I doing wrong here?
I don't think this is actually possible to do, and I may be wrong, but here is why:
It is possible, see second edit.
index.php generates an html webpage (let's call that "index_html")
The <script src="UserInterface.js"></script> tag to implement UserInterface.js is implemented within "index_html".
Therefore: document.getElementById("DebugOutput") and MainPageDoc.getElementByID("DebugOutput") are effectively identical, and they return null because they are both looking for an element with id="DebugOutput".
This <div> is implemented in the first bit of HTML code that I provided <call that "true_index.html">, and not index_html. Therefore, both statements return null as described here.
Edit: I don't think it is possible to edit an HTML element in a parent HTML document from JavaScript that is contained within an iframe. I'll report back after I dig into this some.
Edit: This pretty much sums up the issue, was easy to find once I knew what I was looking for.

Submitting embedded pdf in html form

I've searched in vain for days, but haven't found a solution for my problem yet.
Ideally, I would like to embed a fillable pdf form into an intranet html form for submission to the server for processing (ability to parse the field/values would be gravy, but not required). The files are all in the same domain so no cross-domain issues. I know I could add submission functionality to the pdf form itself, but 1) scripting is beyond the ability of the pdf document administrator and I don't want to take that on, 2) there are hundreds of pdf documents, 3) I need additional scripted fields/values submitted with the form, 4) I want the pdf document to be contained within the login session. So far, the server log shows all the field/values, except the PDFInput parameter which is passed, but the value is empty.
Here's what I have so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(uploadForm).on("submit", function(event) {
var iframe = document.getElementById('PDFObj');
var iframeDocument = [iframe.contentDocument || iframe.contentWindow.document];
var pluginData = iframeDocument;
$(this).append('<input type="file" name="PDFInput" id="PDFInput" value="' + pluginData + '" style="visibility:hidden"/>');
return true;
});
});
</script>
and
<form enctype="multipart/form-data" method="post" name='uploadForm' id='uploadForm'>
<input type='hidden' name='rm' id='rm' value='uploadFile'>
<table align='center'>
<tr>
<td align='left'>
<strong>Notes:</strong>
<br>
<textarea cols='80' rows='2' name='notes' id='notes'></textarea>
<br>
<br>
</td>
</tr>
<tr>
<td colspan=2 align='center'>
<input type='submit'>
</td>
</tr>
<tr>
<td colspan=2>
<br>
<input type='hidden' name='formid' id='formid' value='6F45B3AF-91F3-108C-D3D9-701F541B49DC'>
<iframe type='application/pdf' src="url.pl?formid=6F45B3AF-91F3-108C-D3D9-701F541B49DC.pdf" height='800' width='1000' name='PDFObj' id='PDFObj'>
</td>
</tr>
</table>
</form>
I've tried embedding it using iframe and object along with setting input type="object", but I can't get any combination to work.
Is this even possible? Is there a better approach?
As far as I know, you're not going to be able to capture the PDF data directly from HTML like that. Your best bet is going to be to add submit functionality to the PDFs, then process the resulting FDF data with a server-side script.
You will need either add Submit a Form buttons to your PDFs, or modify the existing buttons. Make sure the form action in the PDF has #FDF after the URI (eg https://example.com/process.php#FDF).
Parsing the data server side is simple. I'm not sure what server side language you are using, but here is a PHP snippet
<?php // process.php, report the data we received
echo '<h2>GET Data</h2>';
foreach( $_GET as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
echo '<h2>POST Data</h2>';
foreach( $_POST as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
Note that a PDF only interacts with a web server properly when viewed inside of a web browser.
I do not know of a reliable way to programmatically add submit buttons to PDFs, nor do I know of a reliable conversion method. You're between a rock and a hard place here IMHO.
More info:
http://www.w3.org/TR/WCAG20-TECHS/PDF15.html
http://etutorials.org/Linux+systems/pdf+hacks/Chapter+6.+Dynamic+PDF/Hack+74+Collect+Data+with+Online+PDF+Forms/

Executing script tags inside innerHTML to perform an Ajax call

I have a 'query builder' page (querybuilder.php) that allows users to build a SQL query and then execute it. All of this works fine.
The parameters of the query are POSTED to another PHP page (queryresults.php) that runs a stored proc and then loops through the results to create a table that is inserted into querybuilder.php. The loop includes a checkbox on each row with the value set to the ID of each record being output.
Queryresults.php (the innerHTML page) also has some dropdowns to allow the user to perform certain actions on the rows that have been 'checked'. I've made a loop outside the Javascript to execute it once for each successive checkbox.
As I understand it - I cannot have script tags in the innerHTML page but I need to interact with the checkboxes that are only created, and assigned a value, when the innerHTML loads.
I've looked at a few workarounds including the following: http://24ways.org/2005/have-your-dom-and-script-it-too but none seem to work.
$checkboxes = isset($_POST['checkbox']) ? $_POST['checkbox'] : array();
foreach($checkboxes as $value) {
echo "
<script>
$('#doAction').on('click', function() {
var id = ".$value.";
var u = document.getElementById('user').value;
$.ajax({
type: \"POST\",
url: \"storedprocs.php\",
data: { id: id, u: user }
})
.done(function(msg) {
document.getElementById('done').innerHTML=msg;
});
});
</script>";
}
The final HTML coming from the innerHTML page looks like this:
echo "
<div class="row">
<div class="col-md-6">
<select id="user" class="input-sm">
<option value="1">User 1</option>
<option value="2">User 2</option>
<option value="3">User 3</option>
</select>
</div>
<div class="col-md-3">
<button class="btn" id="doAction" data-stmt="false">Submit</button>
</div>
</div>
<div class="row">
<div class="leTable">
<table class="table-hover table-responsive">
<tr class="heading">';
echo $tableheaders;
echo '</tr>';
foreach($result as $row) {
echo '<tr>
<td><input type="checkbox" name="chkbox" id="idChkBox">'.$row[0].'</td>';
for ($x=1; $x<sizeof($row); $x++) {
echo '<td>'.$row[$x].'</td>';
}
echo '</tr>';
}
echo '</table>';
echo '</div></div>';
To compound the problem, the element with id=user that the second variable comes from is set by another completely separate innerHTML, so I don't know how to reference that either.
Real head-scratcher, I've googled extensively and trawled through StackExchange to no avail. Any help would be really appreciated!
Thanks!
I think your code could work if it didnt have so many syntax errors. It's document.getElementById, not document.getElementbyId. Beside that you should also end a variable declaration with ;
It all depends on the final rendered page though. We dont know what the final php output is.
I strongly advice you to use a external JavaScript file. Inline JS is bad.

javascript generating php doens't works

Hello I have an option list in html that is created dynamically by php. I want to take the value of the option list withought subbmiting everything and then call another php function to fill another option list. To be more specific I want the user to first pick a University from a database and then to pick a department of that Universe. I 've created dynamicaly the option list for the Uni's by fetching all Uni's from the database and then find the value by javascript. So in the javascript function I want to write php code in order to fetch all the departments from the university. Eveything works fine until I try to call the php function from the javascript.
signup.php
<form>
<table>
.
.
.
<tr>
<td> Ίδρυμα:</td>
<td><select id="selection" name="selection" onchange="selectDep()" >
<?php include './selectUni.php'; ?>
</select> </td>
<td><span id="orgError" style="display: none;"></span> <td>
</tr>
<tr>
<td> Τμήμα:</td>
<td id="dep" name="dep" ></td>
<td><span id="depError" style="display: none;"></span><td>
</tr>
.
.
</table>
</form>
generateDep.js
function selectDep(){
if(document.getElementById('selection').value === "---")
return;
var value=document.getElementById('selection').value;
alert(value);
document.getElementById('dep').innerHTML=" <?php include './selectDep.php'; selectDep("+value+"); ?> ";
return true;
}
the value at the alert is correct
selectDep.php
<?php
//just trying to make this work for now
function selectDep($value){
echo $value;
}
?>
I cannot understand what I am doing wrong. Everything look fine to me. Can you help me?
First You have to understand that the javascript code executes in web browser but the php code executes in web server.
You can use AJAX to fix your problem.
PHP is a server-side scripting language. It is executed on the server, which means the page has to submit values to the server as a trigger. Javascript and HTML are client-side, which means it's all done in the browser without communicating with the server.
To see this in action, right-click on a PHP page in the browser and select to view source. All you will see is the HTML, you will not be able to view any of the PHP code that generates the page. When PHP executes on the server, the result is client-side code (javascript, HTML and maybe CSS) which is sent to the browser.
The browser wouldn't know what to do with PHP code. If you set the inner HTML of an element to some PHP code in client-side script, it won't get executed and all you will achieve is having the browser render the PHP script exactly as you entered it.
In short, the javascript has to submit the selected value back to the server, before the server-side PHP can work out which departments to send back to the browser.

Using PHP DOM parser to get data from Javascript code

I'm learning about parsers and after taking a look at Java parser JSoup I'm trying to do the same with PHP. I'm using PHP Simple HTML DOM (don't now if it's the best solution) to get some data from an url, but without success. How can I take the 8 (near bar1) and 18 (near bar0) numbers from the next code from external web using a PHP parser?
<table>
<tr><td><div name='divns6' id='divns6' style='position:relative;visibility:hidden;'
width='400' height='160'><table valign=botton cellpadding='0' cellspacing='0'
border='0'><tr valign='bottom'>
<td width=15 valign="bottom" height=150><a href="javascript:void(null)"
onMouseOver="changeImage('bar1','','47',2);activadiv('bar0','18');"
onMouseOut="changeImage('bar1','','47',0);desactivadiv('bar1');"><img
NAME="barra1" width="11px" height="47" border="0"></a></td>
<td width=15 valign="bottom" height=150><a href="javascript:void(null)"
onMouseOver="changeImage('bar2','','21',2);activadiv('bar1','8');"
onMouseOut="changeImage('bar2','','21',0);desactivadiv('bar2');"><img
NAME="barra2" width="11px" height="21" border="0"></a></td>
</td></tr></table>
Here's what I've tried, but It only shows the entire line, not only the number:
<?php include ("simple_html_dom.php");
// Create DOM from URL or file
$html = file_get_html('http://www.myurl.com');
// Find all text blocks
$ret = $html->find('a[onMouseOver]');
for ($count='0'; $count<count($ret);$count++) {
echo $ret[$count];
}
?>
With JSoup the line who do the trick was: String onMouseOver = doc.select("a").attr("onMouseOver");
Thank you in advance for your time and dedication.
Finally I've found the solution on my own!!
<?php include ("simple_html_dom.php");
// Create DOM from URL or file
$html = file_get_html('http://www.myweb.com');
// Find all text blocks
$ret = $html->find('a[onMouseOver]');
for ($count='0'; $count<count($ret);$count++) {
echo split("'", $ret[$count])[9]." ";
}
?>

Categories