I am writing a simple PHP/JS script to determine and manage status of all windows terminal servers.
As you know the access via WMI is very slow so I want AJAX to show the progress of each server when he is looping every server.
The code works as expected in firefox.
In chrome the code works, but does not show a status while looping. After the loop the content is displayed.
In IE11 the code does not work. Checking by alerts IE calls both functions and also gets in if statement creating requestobject.
Can somebody help me to get IE working and Chrome showing status?
Thank you for your help.
My code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="tsmanager.css">
<script type="text/javascript">
function refreshall()
{
var table = document.getElementById("terminalservers");
for (var i = 0, row; row = table.rows[i]; i++)
{
var sComputer = row.id;
if (sComputer != "")
{
setTimeout(refresh(sComputer), 2000);
setTimeout(document.getElementById("turn").innerHTML = sComputer, 2000);
}
}
}
function refresh(sComputer)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = function()
{
if (req.readyState == 4 && req.status == 200)
{
document.getElementById(sComputer).innerHTML = req.responseText;
}
}
req.open("GET", "serverrequest.php?name="+sComputer, false);
req.send();
}
</script>
</head>
<body>
<table id="terminalservers">
/* some table content with row id=servername */
</table>
<button onclick="refreshall()">alle</button>
<br><span id="turn">leer</span>
</body>
</html>
I would suggest you look at using jQuery - it provides simple and robust cross-browser support for AJAX and results in much more readable code on all fronts.
Related
I am creating a simple ajax call that retrieves the content of a specified url and writes it to the page. The problem I am having is that it replaces the entire body contents with this information
here is the JS:
(function(){
var mb = window.mb = {};
function get_ad(url, parameters){
var result = "";
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
http_request = new ActiveXObject(avers[i]);
if (http_request){
break;
}
} catch(e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
gen_output(http_request.responseText);
} else {
alert('Error');
}
}
}
http_request.open('GET', url + parameters, true);
http_request.send(null);
}
function gen_output(ad_content){
document.write("<div id=\"mb_ad\">");
document.write(ad_content);
document.write("</div>");
}
get_ad("http://localhost/test/test.html", "");
})();
and here is the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
i am text before <br/>
<script type="text/javascript" src="mb.js"></script>
<br />
i am text after
</body>
</html>
using firebug to inspect, i do not see the text before or the text after, just the <div id="mb_ad"> and the content from the test.html page. If i remove the ajax call and just do 3 document.writes the text before and the text after will display properly. jQuery is not an option, I have to do this without the help of a large library as size and speed are of the essence.
You can't use document.write once the document has completed loading. If you do, the browser will open a new document that replaces the current.
Use the innerHTML property to put HTML code inside an element:
function gen_output(ad_content){
document.getElementById('mb_ad').innerHTML = ad_content;
}
Put the element before the script, so that you are sure that it exists when the callback function is called:
i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>
It doesn't matter much where you place the script, as nothing will be written to the document where it is.
in case you cant control the remote script you might be able to write something like so:
<script>
var tmp = document.write;
document.write = function () {
document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;
Well it is a nasty hack but it seems to work...
var div = document.createElement('div');
div.id = 'mb_ad';
div.innerHTML = ad_content;
Now, you can append this node wherever you want it to be.
you can use <script>document.body.innerHTML+="//Your HTML Code Here";</script>
Same Leon Fedotov answer but more jQuery
{
var old_write = document.write;
var $zone = $('.zone.zone_' + name);
// redefine document.write in this closure
document.write = function () {
$zone.append([].concat.apply([], arguments).join(''));
};
// OA_output[name] contains dangerous document.write
$zone.html(OA_output[name]);
document.write = old_write;
}
I had the same problem with the following code :
$html[] = '<script>
if($("#mf_dialogs").length == 0) {
document.write("<div id=\"mf_dialogs\"></div>");
}
</script>';
The following code replaces document.write efficiently :
$html = '<div id="dialogHolder"></div>
<script>
if($("#mf_dialogs").length == 0) {
document.getElementById("dialogHolder").innerHTML="<div id=\"mf_dialogs\"></div>";
}
</script>';
The way you can emulate document.write somewhat is the following code:
<script>
(function(script) {
var parent = script.parentNode;
var node = document.createTextNode('Surprise!');
parent.replaceChild(node, script);
})(document.currentScript);
</script>
This way you can put arbitrary HTML in place of a script element. If you have a simpler case, like you can wrap a script in another tag, you can do even simpler version.
<script>
document.currentScript.parentElement.innerHTML = 'Surprise!';
</script>
I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.
It works for Firefox but not for Chrome and IE.
I try it on local.
I get error on httpObj.send( null ); line.
How can i handle this problem ?
HTML File
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XML READ</title>
<script type="text/javascript">
//---
function GetXml() {
if (window.XMLHttpRequest) {
var httpObj = new XMLHttpRequest();
} else {
var httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
httpObj.open("GET", "notification.xml", false);
// Error Starts Here
httpObj.send( null );
var xmlDocument = httpObj.responseXML;
var xmlEl = xmlDocument.getElementsByTagName("haber");
//--
for (i = 0; i < xmlEl.length; i++) {
for (j = 0; j < xmlEl[i].childNodes.length; j++) {
if (xmlEl[i].childNodes[j].nodeType != 1) {
continue;
}
alert(xmlEl[i].childNodes[j].firstChild.nodeValue);
}
}
}
</script>
</head>
<body onload="GetXml()">
</body>
</html>
XML File
<?xml version="1.0" encoding="utf-8" ?>
<notifications>
<notification id="001">
<name>First</name>
</notification>
<notification id="002">
<name>Second</name>
</notification>
</notifications>
Your code works in chrome and IE if you replace
xmlDocument.getElementsByTagName("haber");
with
xmlDocument.getElementsByTagName("notification");
Also when you say I try it on local make sure that it is hosted in a server e.g. apache and the server is running
Old comment:
check this link about browser combatibility and correct ajax call
http://www.w3schools.com/ajax/ajax_xmlfile.asp
I am new in learning AJAX and stuck in the first program. Tried to debug but unable to do so.
Below is my code snippet
----------input-ajax.html-------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML PAGE</title>
<script type="text/javascript">
var request=null;
function createRequest(){
try{
request= new XMLHttpRequest();
)catch(e){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request=null;
}
}
}
if(request==null){
alert("Error Creating Request Object");
}
}
function getName(){
alert("getname called");
createRequest();
var url = "showName-ajax.jsp";
request.open("POST",url,true);
alert("before");
request.onreadystatechange = updatePage;
alert("after");
request.send(null);
}
function updatePage(){
//var newName= request.getResponseHeader("r1");
var newName= request.responseText;
var name1 = document.getElementById("name");
replaceText(name1,newName);
}
function replaceText(el, text) {
if (el != null) {
clearText(el);
var newNode = document.createTextNode(text);
el.appendChild(newNode);
}
}
function clearText(el) {
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
el.removeChild(childNode);
}
}
}
}
</script>
</head>
<body>
<h1>WELCOME <span id="name"> GUEST</span></h1>
<form method="POST">
<input type="text" name="t1">
<input type="button" value="Show Name" onclick="getName();"/>
</form>
</body>
</html>
----------showName-ajax.jsp------------
<%
String s1=request.getParameter("t1");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(s1); // Write response body.
%>
But When I run the program (click on the button) nothing happens. Even the alert message that getName function is called does not appear. PLEASE HELP!!!!
Typo:
)catch(e){
should be
}catch(e){
This would show up as an error in the console of your browser. Be sure to always check that first if things don't work like they should.
You have a ) instead of a } here:
try{
request= new XMLHttpRequest();
)catch(e){
So your function never gets defined.
change )catch(e){ to }catch(e){
but
why are you creating request object everytime on button click?
you just need to call "createRequest()" only once on page load event.
I am creating a simple ajax call that retrieves the content of a specified url and writes it to the page. The problem I am having is that it replaces the entire body contents with this information
here is the JS:
(function(){
var mb = window.mb = {};
function get_ad(url, parameters){
var result = "";
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
http_request = new ActiveXObject(avers[i]);
if (http_request){
break;
}
} catch(e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
gen_output(http_request.responseText);
} else {
alert('Error');
}
}
}
http_request.open('GET', url + parameters, true);
http_request.send(null);
}
function gen_output(ad_content){
document.write("<div id=\"mb_ad\">");
document.write(ad_content);
document.write("</div>");
}
get_ad("http://localhost/test/test.html", "");
})();
and here is the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
i am text before <br/>
<script type="text/javascript" src="mb.js"></script>
<br />
i am text after
</body>
</html>
using firebug to inspect, i do not see the text before or the text after, just the <div id="mb_ad"> and the content from the test.html page. If i remove the ajax call and just do 3 document.writes the text before and the text after will display properly. jQuery is not an option, I have to do this without the help of a large library as size and speed are of the essence.
You can't use document.write once the document has completed loading. If you do, the browser will open a new document that replaces the current.
Use the innerHTML property to put HTML code inside an element:
function gen_output(ad_content){
document.getElementById('mb_ad').innerHTML = ad_content;
}
Put the element before the script, so that you are sure that it exists when the callback function is called:
i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>
It doesn't matter much where you place the script, as nothing will be written to the document where it is.
in case you cant control the remote script you might be able to write something like so:
<script>
var tmp = document.write;
document.write = function () {
document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;
Well it is a nasty hack but it seems to work...
var div = document.createElement('div');
div.id = 'mb_ad';
div.innerHTML = ad_content;
Now, you can append this node wherever you want it to be.
you can use <script>document.body.innerHTML+="//Your HTML Code Here";</script>
Same Leon Fedotov answer but more jQuery
{
var old_write = document.write;
var $zone = $('.zone.zone_' + name);
// redefine document.write in this closure
document.write = function () {
$zone.append([].concat.apply([], arguments).join(''));
};
// OA_output[name] contains dangerous document.write
$zone.html(OA_output[name]);
document.write = old_write;
}
I had the same problem with the following code :
$html[] = '<script>
if($("#mf_dialogs").length == 0) {
document.write("<div id=\"mf_dialogs\"></div>");
}
</script>';
The following code replaces document.write efficiently :
$html = '<div id="dialogHolder"></div>
<script>
if($("#mf_dialogs").length == 0) {
document.getElementById("dialogHolder").innerHTML="<div id=\"mf_dialogs\"></div>";
}
</script>';
The way you can emulate document.write somewhat is the following code:
<script>
(function(script) {
var parent = script.parentNode;
var node = document.createTextNode('Surprise!');
parent.replaceChild(node, script);
})(document.currentScript);
</script>
This way you can put arbitrary HTML in place of a script element. If you have a simpler case, like you can wrap a script in another tag, you can do even simpler version.
<script>
document.currentScript.parentElement.innerHTML = 'Surprise!';
</script>