I'm trying to re-write table using javascript and ajax. Here request has been sent and response is arrived but innerHTML cannot re-write table content with response text.
Here is my code.
<table>
<tbody id='product1'>
<tr>
<td> Product Name:</td>
<td>P1</td>
</tr>
</tbody>
</table>
Javascript
function compareProd(prodID,tId){
browse();
var url = 'process.jsp';
url += '?compareProd='+prodID;
xmlHttp.onreadystatechange = changeProd(tId);
xmlHttp.open('POST', url, true);
xmlHttp.send(null);
}
function changeProd(tID) {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete') {
document.getElementById('product1').innerHTML = xmlHttp.responseText;
}
}
process.jsp
<tr>
<td> Product Name:</td>
<td>P2</td>
</tr>
here response is arrived but cannot rewrite table.
try it in single function and check like this, on assumption that you initialized xmlHttp request object.
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
document.getElementById('product1').innerHTML = xmlHttp.responseText;
}
};
Related
I am using a JavaScript & Ajax to make a php call to return data from my database. The call returns the data as it should, but when the page fully loads the <div> tags value is cleared.
What do I need to change in my syntax so that the div tag retains the value echo from the php file? I checked the Console and it is only showing page load info and nothing related to this issue (at least not that I saw).
<form id="form1" method="post">
<div id="results"> </div>
<div style="padding-top: 10px;"><input type="submit" value="Submit" onclick="MakeQuery()" /></div>
<script type="text/javascript">
var xhttp;
function MakeQuery()
{
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4 && xhttp.status==200)
{ document.getElementById("results").innerHTML = xhttp.responseText; } }
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}
</script>
</form>
I think you need to prevent the actual form submit before using AJAX:
var xhttp;
function MakeQuery(event) {
event.preventDefault(); // Cancel form submit, use AJAX
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}
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>
I have a dataSend AJAX function that I am calling onclick but it is not getting called.
I checked the it in the Inspector of my browser and it the click handler attached to it and yet when I put a breakpoint in the function using the Debugger, it never reaches there.
PHP/HTML Snippet (RAW)
<td onclick="dataSend('<?php echo $year;?>','12','<?php echo $rs->StudentId;?>');"><?php echo $count12[$rs->StudentId]."/248"; ?></td>
Now, this is cluttered because of the PHP, here's how it looks after being run in the browser.
After running on browser
<td class=" " onclick="dataSend('2015','02','186');">/224</td>
AJAX Snippet (Function)
function dataSend(year, month, studentid) {
parameters = 'StudentId='+studentid+'&Month='+month+'&Year='+year;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('iframe').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'attendancestu.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
FYI - This function is not inside any other function or trigger. It is not even inside $(document).ready();
I've written codes like this hundreds of times but I can't seem the figure out the problem here
You can rewrite this to another binding level which also makes the structure of your table way easier to read.
<td class="send-data" data-year="<?= $year ?>" data-month="12" data-student-id="<?= $rs->StudentId ?>"><?= $count12[$rs->StudentId]."/248"; ?></td>
<script>
$( document ).on( 'click', '.send-data', function( e ) {
//stop everything what would happen on click of td
e.stopPropagation();
e.preventDefault();
// keep track of the clicked item
_this = $( this );
studentId = _this.data( 'student-id' );
month = _this.data( 'month' );
year = _this.data( 'year' );
parameters = 'StudentId='+studentId+'&Month='+month+'&Year='+year;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('iframe').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'attendancestu.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
});
Please load JS before HTML. Means Put your js files in
Also change parameters to this:
parameters = window.location.href + '/StudentId='+studentid+'&Month='+month+'&Year='+year;
And try to run it LIVE OR localhost
I currently use a java-script function to load content based on a selection, here is an example of the function
function loadActions2(id,value,title) {
var url = title+"?value="+value;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiceXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
divtarget.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
}
This will load a php file, with desired content.
My main site looks like this
<table>
<tr>
<td> Text 1234</td>
<td>
<label onclick"loadActions2('id','value','title')"> Click here</label>
</td>
</tr>
</table>
and the loaded php file contains another table.
Now, im looking for a solution, to add the content of the file directly to the table, so this would mean, my php file would look like this
<tr>
<td>Text 999</td>
</tr>
And should be added directly to the existing table, not in a seperate div/table.
Is this possible?
Assign id to the table, and when request is successful, append HTML to the table:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("mytable").innerHTML += xmlhttp.responseText;
}
}
As pointed out by user Gothdo, assign an ID to the table tag.
<table id="myTable">
<tr>
<td> Text 1234 </td>
</tr>
<td> <label onclick="loadActions2('id','value','title');"> Click here </label> </td>
</tr>
</table>
then, when the request(s) arrive, you just append the response getting the ID from the table:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var content = xmlhttp.responseText;
var node = document.createElement("tr");
var textNode = document.createTextNode(content);
node.appendChild(textNode);
document.getElementById("myTable").appendChild(node);
}
}
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;
}
}