Getting a getXMLHTTP is not defined error - ajax

Here is my javascript:
<script type="text/javascript">
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
//ERROR is right here
//UNCAUGHT REFERENCE ERROR: getXMLHTTP IS NOT DEFINED
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
It is being called from this:
<tr>
<td width="150">Country</td>
<td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option> </select></td>
</tr>
Just to be safe, this is my header, maybe I am doing this incorrectly?
<head>
<link rel="stylesheet" type="text/css" href="view/css/application.css" />
<script type="text/javascript" src="view/javascript/application.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
Another note, I am working off this example and he is using a mysql server, I am using ODBC to connect to an Access database. Would I not use xmlHTTP for this? I honestly don't know.

Your getXMLHTTP() should look like this :
<script type="text/javascript">
function getXMLHTTP() {
var x = false;
try {
x = new XMLHttpRequest();
}catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
function getState(countryId){
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req){
req.onreadystatechange = function(){
if (req.readyState == 4){
if (req.status == 200){
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>

Related

ws.onmessage not called even though server is sending data

I'm using sockjs-0.3.4.
Before change page structure, it worked normally.
However after changing some stuff. abrubtly ws.onmessage function is beginning not to called.
I checked the connection with server by looking into devtools.
It looks like getting data from the server.
Please help me to know what's the point to check out.
enter image description here
var statusWatcher = {
curPage:"",
ws: null,
wsBaseUrl :null,
uid: null,
init : function(url ){
if(statusWatcher.ws != null) return;
console.log(statusWatcher.ws);
console.log("wsBaseUrl:"+url)
statusWatcher.wsBaseUrl = url;
var browserSupport = ("WebSocket" in window)? true: false;
if(browserSupport){
statusWatcher.start();
}else{
console.log("WebSocket is Not supported by your Web Browser!");
}
//log.eventHandler(1);
},
start : function(){
baseWsURL = statusWatcher.wsBaseUrl+"/statusCheck?&uid="+statusWatcher.uid;
console.log("web socket baseurl:"+baseWsURL);
try{
statusWatcher.ws = new WebSocket(baseWsURL);
} catch (e){
console.log(e);
}
statusWatcher.ws.onopen = function() {
console.log("web socket Opened! ");
};
statusWatcher.ws.onclose = function() {
console.log("web syslog socket Closed! ");
};
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
statusWatcher.ws.onmessage = function(evt) {
console.log("get message...");
//console.log("page:"+curPage);
var data = evt.data;
console.log(data);
var msg;
if(curPage =="main") return;
var e = JSON.parse(data);
if(e.status =="COMPLETE"){
$("#" + e.groupId).text("complete");
$("#" + e.groupId).removeClass('run error');
$("#" + e.groupId).addClass('complete');
statusWatcher.updateScoreState(e.groupId, "COMPLETE", e.topRplRate,e.topKwdRate);
}else if(e.status == "ERROR"){
$("#" + e.groupId).text("error");
$("#" + e.groupId).removeClass('run complete');
$("#" + e.groupId).addClass('error');
statusWatcher.updateScoreState(e.groupId, "ERROR");
}else{
$("#" + e.groupId).html("running("+e.progress+"/"+e.total+")");
$("#" + e.groupId).removeClass('error complete');
$("#" + e.groupId).addClass('run');
statusWatcher.updateScoreState(e.groupId, "RUNNING");
}
};
},
}
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<script src="<c:url value="js/fileuploadMain/statusWatcher.js"/>"></script>
</head>
<body>
<!--header-->
<c:import url="/WEB-INF/jsp/fileupload/header.jsp" />
<!--contents-->
<div class="contents">
<div class="container" id="container">
</div>
</div>
<script>
$(document).ready(function() {
var nice = $("html").niceScroll(); // The document page (body)
$(".select-items").niceScroll({
zindex: "auto",boxzoom:false
});
$("#container").load("group.do");
calaendar.init();
var wsBaseUrl = "ws://"+document.location.host+"<c:out value="${pageContext.request.contextPath}"/>";
statusWatcher.init(wsBaseUrl);
});
</script>
</body>
</html>
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
I changed upper source code to the next.. Maybe I remove the function name mistakenly..
statusWatcher.ws.onerror = function(err) {
console.log("web syslog socket Error: " + err);
};

XML data pasing

Hi I am trying to display data from XML file to unordered list. Any help would be great. I do have an XML file books data wherein trying to print or display the books author etc.
<!DOCTYPE html>
<html>
<style>
</style>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
report(this);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function report(xml){
var i;
var xmlDoc=xmlhttp.responseXML;
var table = "";
var x = xmlDoc.getElementByTagName("CD");
for(i=0; i<x.length; i++){
table+="<li>" + x[i].getElementByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</li>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
<body>
<ul id="demo"></ul>
<button type="submit" onclick="loadDoc()">RUUUUNNNNN</button>
</body>
</html>

Browser does not render appended child node

I'm experimenting with web service to transmit new elements to document DOM.
So I'm preparing a XML on server side with necessary informations to do that job. My server side XML is as followed:
<Root>
<Command>Add
<Data><button id="PB" style="width:600px; height:100px;"/></Data>
</Command>
</Root>
This XML will be caught by following page.
You will see XML has a command id "Add", which should add the nodes below data to the page.
When code is running, the button will be created and shown properly in document DOM (see code function onMessage), but it will not be rendered.
The browser debugger tells me, the width and height of the button seems to be Null. When I edit the attributes in browser debugger, the button will be rendered after change. I get this behaviour on Chrome and IE.
I need a hint, what has to be changed to let it run.
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8002/chat";
var output;
var websocket;
"use strict";
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var parser, xmlDoc, NodeCommand, but;
parser = new DOMParser();
xmlDoc = parser.parseFromString(evt.data, "text/xml");
NodeCommand = xmlDoc.getElementsByTagName("Command");
switch (NodeCommand[0].textContent) {
case "Add":
output.appendChild(NodeCommand[0].childNodes[1].childNodes[0]);
break;
}
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Solved!
This can't be done in this (intuitive) way. Elements have to be created over document.

How to keep Websocket API session alive

I'm trying to keep subscribed to blockchain.info websocket api for new blocks. I basically took the code off http://www.websocket.org/echo.html and plugged in blockchain.info parameters. It works, but I'm finding that after a while it will automatically disconnect. How do I keep the session alive?
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "wss://ws.blockchain.info/inv";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("{\"op\":\"blocks_sub\"}");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
//websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
I just tested this, and it seems to work:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready
(
function(){
initWebSocket();
}
);
</script>
<script language="javascript" type="text/javascript">
function initWebSocket()
{
// init blockchain websocket (activity, blocks)
var blockchain = new WebSocket('ws://ws.blockchain.info:8335/inv');
blockchain.onerror = function (error){ console.log('connection.onerror',error); };
blockchain.onopen = function ()
{
blockchain.send( JSON.stringify( {"op":"unconfirmed_sub"} ) ); // subscribe to uncofirmed activity
};
blockchain.onmessage = function (message)
{
var response = JSON.parse(message.data);
var date = new Date(0);
date.setUTCSeconds( response.x.time );
if( response.op == "utx")
{
var amount = 0;
for(var i=0;i<response.x.out.length;i++)
amount += response.x.out[i].value;
// amount is in satoshi
// 1 BTC = 100,000,000 Satoshi (https://en.bitcoin.it/wiki/activity)
response.amount = amount / 100000000;
}
console.log( response.op, response );
};
}
Largely taken from here: http://bl.ocks.org/npedrini/6030317

AJAX: I am unable to fetch the data from server side

I need to get output from my server side code but i am able to fetch it.
I have used script manager and script manager proxy control in master page.
How can i get the string that is being returned from the cs file
Here is my Default.aspx code
<asp:UpdateProgress runat="server">
<ProgressTemplate >
Loading..........
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label ID="lbl" Text="Enter Your Name" runat="server"></asp:Label>
<input type="text" id="txt" /><br />
<input type="button" id="btn" value="Submit" onclick="makeGetRequest()" />
<div id="description">Hello</div>
</ContentTemplate>
</asp:UpdatePanel>
<script language="Javascript" type="text/javascript" >
function createRequestObject() {
var tmpXmlHttpObject;
if (window.XMLHttpRequest) {
// Mozilla, Safari would use this method ...
tmpXmlHttpObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE would use this method ...
tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
return tmpXmlHttpObject;
}
var http = createRequestObject();
function makeGetRequest() {
http.open('post', 'Default.aspx/greet',true);
//assign a handler for the response
http.onreadystatechange = processResponse;
//actually send the request to the server
http.send(null);
}
function processResponse() {
if (http.readyState == 4) {
var response = http.responseText.toString();
alert("Inside here before");
document.getElementById('description').innerHTML = response;
alert("Inside here after");
}
}
</script>
// my default.aspx.cs file
[WebMethod(EnableSession=false)]
public static string greet()
{
return "hello";
}
I am getting all contents of the page copied instead of getting response from it
the line var http = createRequestObject(); have to be the first line inside function makeGetRequest() function. anyway, i am posting a working code.
<script language="Javascript" type="text/javascript" >
function makeGetRequest() {
var http;
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var response = http.responseText.toString();
alert("Inside here before");
document.getElementById('description').innerHTML = response;
alert("Inside here after");
}
}
http.open('post', 'Default.aspx/greet', true);
http.send(null);
}
</script>

Resources