How to transfer clicked table row data to input while being updated - javascript

I am currently having a table which is being updated every 2 seconds using jsAjax.
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divid").innerHTML=xmlhttp.responseText; // div
}
}
xmlhttp.open("GET","url",true); // php file
xmlhttp.send();
}
window.setInterval(function(){
loadXMLDoc();
}, 1000);
</script>
In html there is only a div. The script is having path to a php file which prints a table every 2 second by fetching data from db. I want user to be able to click on any row and transfer the row content to the input area. I tried the following:-
<script>
var table = document.getElementById('table');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
//rIndex = this.rowIndex;
var texte1 = this.cells[0].innerHTML;
var texte2 = this.cells[1].innerHTML;
var texte3 = this.cells[2].innerHTML;
document.getElementById("Someinput1").value = texte1;
document.getElementById("Someinput2").value = texte2;
document.getElementById("Someinput3").value = texte3;
};
}
</script>
but this does not seem to work when table is being updated every 2 second but it works when it is not. It would be appreciated to help me out on how to fetch the table row data while it is also being updated live.
Sample Table:-
<thead>
<tr id='id_buy_orders_header'>
<td>Amount</td>
<td>Price</td>
<td>Total</td>
</tr>
</thead>
<tbody id='id_buy_orders_body'>";
while ($row = mysqli_fetch_array($qlr1))
{
echo '<tr>
<td>'.$row['sum(amount)'].$coin.'</td>
<td>'.$row['price'].$bm.'</td>
<td>'.$row['sum(total)'].$bm.'</td>
</tr>';
}
echo "</tbody>
</table>";

Related

alert(status) in javascript always results in null

I have a php page which I want to give me dynamically result from the drop down list I am choosing. The detail regarding the choosed option is saved in the database. So, basically to get the detail from the DB dynamically when I choose an option.
First Page from where I am selecting the data (Here the data is events)
<form name="ParticularFest" action="" method="post">
<table align="center">
<tr>
<tr><td><br/></td></tr>
<td><h4>Fest Name: </h4></td>
<td>
<select name="EventId" id="EventId" onchange="javascript: return ParticularValidate();"><option>Select Event</option>
<?php
$sql="Select EventName,MEventId from Tbl_Main where Status=0 and CategoryId=1";
$stmnt=sqlsrv_query($conn,$sql);
while( $row = sqlsrv_fetch_array( $stmnt,SQLSRV_FETCH_BOTH))
{
echo'<option value="'.$row["MEventId"].'">'.$row["EventName"].'</option>';
}
?>
</select>
</td>
</tr>
</table>
<div id="display"></div>
</form>
<script type="text/javascript">
function ParticularValidate() {
var errorMessage = null;
var MEventId = document.ParticularFest.EventId.value
var status = null;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
//alert("firefox");
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
status = xmlhttp.responseText;
document.ParticularFest.display.innerHTML = status;
}
}
xmlhttp.open("GET", "ParticularValidate.php?MEventId=" + MEventId, true);
xmlhttp.send();
}
</script>
The next page is the one to which I am redirecting, i.e. the ParticularValidate.php
<?php
include_once("Db.php");
$MEID=$_REQUEST['EventID'];
$obj=new Db;
?>
<table align="center">
<tr>
<th width="200" align="center"><br/><h3><b>Program Name</b></h3></th>
<th width="340" align="center"><br/><h3><b>Name</b></h3></th>
<th width="200" align="center"><br/><h3><b>Mobile No.</b></h3></th>
<th width="200" align="center"><br/><h3><b>Email</b></h3></th>
<th width="200" align="center"><br/><h3><b>College Name</b></h3></th>
<tr><td><br></td></tr>
</tr>
<?php
$sql="select distinct na.ProgramName,ma.Name,ma.Mob,ma.Email,ma.CName from Tbl_Main as sa inner join Tbl_UserProgram as ra on sa.MEventId=ra.EventId inner join Tbl_UserReg as ma on ma.UserId=ra.UserId inner join Tbl_Program as na on ra.PgmId=na.ProgramId and sa.MEventId='$MEID'";
$stmnt=sqlsrv_query($conn,$sql);
while($row = sqlsrv_fetch_array($stmnt,SQLSRV_FETCH_BOTH))
{
echo
'<tr align="center">
<td>'.$row["ProgramName"].'</td>
<td>'.$row["Name"].'</td>
<td>'.$row["Mob"].' </td>
<td>'.$row["Email"].'</td>
<td>'.$row["CName"].'</td>
<tr><td><br></td></tr>
</tr>';
}
?>
</table>
Both one are saved as .php
The data fetched from the DB (the select query) is working fine in the DB query.
Always the status is null.
I tried to see whether the status is fetching the data, whether it is mere the display part, which is the problem. But always the result to these are Null. I am a noob in these, so please throw me suggestions.
Thank You in advance.
Edit 1:
I tried to check whether this:
var MEventId=document.ParticularFest.EventId.value
is getting the MEventId, and yes it is. It is sending the MEventId too. The problem seems to be in the second php Page. I am not getting any return from that page. (I tried alert(status) in almost everywhere in the first php page, and it shows Null popup always :D )
Edit 2:
This is done in localhost. It is a college mini project
your alert is happening immediately, before the request finishes.
Try something like this.
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('test.html'); };
function makeRequest(url) {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>

javascript countdown and updates database php

I would like to implement a JavaScript code to count down hundred seconds. I have written the code for count down, but I need the value of the remaining time and update it in a database on every second. Below is an example of what I would like to accomplish:
On Every second I would like to run:
UPDATE 'table' SET 'timeleft=[remaining time]'
Is this possible?
Below is what I've tried so far:
<? $time = "100"; ?>
<script>
var intCountDown = <?php echo $time; ?>;
function countDown()
{
if(intCountDown < 0)
{
cntdwn.innerText = 'Done';
return;
}
cntdwn.innerText = intCountDown--;
setTimeout("countDown()",1000);
}
</script>
Then just: <div id=cntdwn></div>
Additionally this may help clarify my intention: I want to implement a single-shot timer but prefer the counter to overflow back to where it started after the page refresh.
To do that, you'll need AJAX:
here is your AJAX function:
function loadXMLDoc(timeleft)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
cntdwn.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update.php?timeleft="+timeleft,true);
xmlhttp.send();
}
Using above function, we can send an int to update.php?timeleft= and update.php should connect to database and update your timeleft value (i think you wrote it anyway). and in your countdown function just replace this line:
cntdwn.innerText = intCountDown--;
with this(since we will update innerText in ajax call):
intCountDown--;
that's all needs to be done

Select a dropdown list option, and set it as a javascript variable

Once a dropdown list option is selected, I would like to hold that selected option as a javascript variable.
To make this a little more complex, the variable should be held inside the page's main Ajax coding, so it is not lost when different Ajax content is loaded.
Here's my wonderfully basic form code:
<form name="searchLocations" method="POST">
<select name="locationName">
<?php
$sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
}
?>
</select>
<button onclick="loadXMLDoc(indexSearchingSubmit);" id="searchingSubmit">Search</button>
</form>
and here is my main ajax code, where the form dropdown variable should be held so it can be used later:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
Using jQuery:
$('[name="locationName"]').change(function() {
YOUR_VAR = $(this).attr('value');
});
Not using jQuery-
Add onChange() to your SELECT element, also added id attribute.
Add javascript onchange handler function, which just retrieves the selected value and sets your var
<select name="locationName" onChange="setSelected()" id="locationSelect">
function setSelected(){
var myselect= document.getElementById("locationSelect");
YOUR_VAR = myselect.options[myselect.selectedIndex].value;
}

Using JSON to parse xmlhttp.responseText for populating textboxes

How can JSON be used to parse xmlhttp.responseText? I can't seem to get textboxes populated using the parsed data. I tried using .value and .innerHTML with the dot notation with b.first and b.second used with json_encode from the loadTextBox.php file (see below), but the textboxes won't populate.
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = xmlhttp.responseText;
var b = JSON.parse(a);
document.getElementById("textbox").innerHTML=b.first;
document.getElementById("textbox2").innerHTML=b.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query("SELECT column_one FROM table_one");
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
This is fully tested and works. Use as a starting point to accomplish what you are trying to do:
var url = "YOUR.php"
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.send(null);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && (ajax.status == 200)) {
console.log("ready")
var Data = JSON.parse(ajax.responseText);
console.log(Data);
console.log(Data.first);
} else {
console.log("not ready yet")
}
}
This assumes your JSON output is properly formatted as you stated:
{"first":"radim","second":"radi"}
I have figured out the underlying problem. Extra tags were being sent because I had unnecessary tags in my DB info file. Those tags were being sent in the responseText with {"first":"radim","second":"radi"}. So the code pertaining to ---Placeholder for correct DB login info--- was wrong. I also changed .innerHTML to .value and now it works as intended.
Main page code updated:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}

Parse an HTML Table returned from an ASP page using AJAX and Extract Specific Cells

There is an ASP page on work intranet that returns data from numerous sensors. The data is presented in table format with several rows and columns.
I thought it would be cool if I could display a few of the outputs on our department website.
I would like to use ajax to open the ASP page and get a few data points from the resulting table.
Opening up the page with AJAX was easy enough, but I'm not sure what to do with it after that.
The table is formatted like so:
<table>
<tr>
<td>Data ID 1</td>
<td>Description</td>
<td>Data</td>
</tr>
<tr>
<td>Data ID 2</td>
<td>Description</td>
<td>Data</td>
</tr>
</table>
The first cell in each row is a unique ID, then the 5th column in the same row has the value I want.
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("testDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://plantdata/showData.asp",true);
xmlhttp.send();
}
How can I grab the data by the unique ID?
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var target = document.getElementById("testDiv");
target.innerHTML = xmlhttp.responseText;
extractIDs(target);
}
}
function extractIDs(container) {
var trs = container.getElementsByTagName("TR");
for (var i=0; i<trs.length; i++) {
var tds = trs[i].getElementsByTagName("TD"),
txt = tds[0].textContent || tds[0].innerText; // innerText for IE
alert("row " + (i+1) + ": " + txt);
}
};
This is a job for jQuery for sure. Can I see the output and then I will show you the answer, but it is along these lines:
$(document).ready(function () {
$.ajax({
url: "TableData.html",
type: "GET",
success: function (data) {
var tempData = $(data);
//alert(tempData.html());
tempData.find("tr td[id]").each(function (i) {
alert($(this).siblings(":nth-child(5n)").text());
});
}
});
});
Loop through the table's rows:
var data;
var rows=document.getElementById("testDiv").getElementsByTagName('table')[0].rows;
for(var i=0; i<rows.length; ++i)
{
var cells=rows[i].cells;
if(cells[0].innerHTML == uniqueID)
{
data=cells[4].innerHTML;
break;
}
}

Categories