The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. February 11, 2012, 11:32:02 PM

Login with username, password and session length


Pages: 1 [2]
  Print  
Author Topic: responseText vs. responseXML  (Read 6663 times)
perkiset
Olde World Hacker
Administrator
Lifer
*****
Online Online

Posts: 9792



View Profile
« Reply #15 on: December 16, 2008, 08:12:52 PM »

First off, I assume you are running Safari, yes? And have the Develop/Show Error Console window up?

Hang tough, I'll debug it right quick.

/p

Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Online Online

Posts: 9792



View Profile
« Reply #16 on: December 16, 2008, 08:38:04 PM »

Awright, a couple issues with it - sorry I was going fast and I thought that you'd be able to debug it if there were troubles.

The 2 biggest troubles - I hope you added a source line to pull down the ajaxRequestor class so that it was available to the page - in my example I don't reference it anywhere.  Roll Eyes Second, it seems that the forum software adds text gremlins to the source, so if you just copy/paste and try to run it you may get immediate and really weird troubles. In BBE or TextWrangler, select Text/Zap Gremlins to get rid of the weirdness. In other editors you could probably say, "Show Invisibles" and you'll see what I mean.

Here is code that is just slightly tweaked for better effect. It 100% works. Also at the bottom is a reprint of the ajaxRequestor class just for good measure - and another little ditty, dumpArray() which I use for debugging that you can play with. It's pretty handy.

The main html page:
Code:
<html>
<head>
<script src="/class.ajaxRequestor.js"></script>
<style>
#resultBox {
height: 300px;
width: 500px;
margin: 0 auto;
margin-top: 20px;
border-color: black;
border-style: solid;
border-width: 1px 2px 2px 1px;
background-color: #a0a0a0;
}
#selectType {
margin-right: 20px;
}
</style>
</head>
<body>

<div style="text-align: center">
<select id="selectType">
<option value="0">Simple Update</option>
<option value="1">JSON Array</option>
<option value="2">Javascript Redirect</option>
<option value="3">Preformatted HTML</option>
</select>
<input id="testbutton" type="button" value="Test" onClick="test()">
</div>

<div id="resultBox" style="">&nbsp;</div>

<script>
req = new ajaxRequestor();
req.url = '/handler.php';

resArr = new Array();

function test()
{
var target = document.getElementById('selectType');
var which = target.options[target.selectedIndex].value - 0;
req.postParam('request', which);
switch(which)
{
case 0:
// This option will hide the test button..
hideButton();
req.onSuccess = function(sender) { showButton(); document.getElementById('resultBox').innerHTML = 'Response received: ' + sender.lastResponse; }
break;

case 1:
// This one too.
hideButton();
req.onSuccess = handleJSON;
break;

case 2:
req.onSuccess = function(sender) { eval(sender.lastResponse); }
break;

case 3:
req.onSuccess = function(sender) { document.getElementById('resultBox').innerHTML = sender.lastResponse; }
break;
}
req.execute();
}
function hideButton()
{
document.getElementById('testbutton').style.display = 'none';
}
function showButton()
{
document.getElementById('testbutton').style.display = 'inline';
}
function handleJSON(sender)
{
showButton();
try
{
resArr = eval('(' + sender.lastResponse + ')');
document.getElementById('resultBox').innerHTML = dumpArray(resArr);
} catch(e) {
alert('Result from server was not valid JSON code. Response was: ' + sender.lastResponse);
}
}
</script>
</body>
</html>

Meanwhile at the server, handler.php:
Code:
<?php

$reqType
=$_POST['request']-0;

switch(
$reqType)
{
case 0:
die('OK: ' date('H:i:s'time()));

case 1:
$newArr['a']=1234;
$newArr['b']=2345;
$newArr['c']=3456;
$arrStr json_encode($newArr);
echo $arrStr;
break;

case 2:
echo"top.location='http://www.google.com/';";
exit;

case 3:
echo<<<HTML
<center>
<h1>Hello World!</h1>
<h3>Four score and seven years ago, our fathers brought forth<br>
to this country - a new nation - conceived in liberty and dedicated<br>
to the proposition that all men are created equal.<br><br>

Or something like that.
</h3>
HTML;
break;
}

?>



And finally, at the server, the source for class.ajaxRequestor.js:
Code:
function dumpArray(arr, level)
{
var dumped_text = "";
if (!level) { level = 0; }

// The padding given at the beginning of the line.
var level_padding = "";
for (var j=0; j<level; j++) { level_padding += '   '; }

if (typeof(arr) == 'object')
{
// Array, Hashes & Objects
for (var item in arr)
{
var value = arr[item];
 
if (typeof(value) == 'object')
{
// If it is an array...
dumped_text += level_padding + "['" + item + "']\n";
dumped_text += dumpArray(value,level+1);
} else {
vSurround = (typeof(value) == 'string') ? "'" : '';
nSurround = (item.match(/^[0-9]{1,10}$/)) ? '' : "'";
dumped_text += level_padding + "[" + nSurround + item + nSurround + "] => " + vSurround + value + vSurround + "\n";
}
}
} else {
// Stings, Chars & Numbers etc.
dumped_text = "(" + typeof(arr) + ") " + arr + "\n";
}

return dumped_text;
}

// ----------------------------------------------------------- //
//                       ajaxRequestor                         //
// ----------------------------------------------------------- //
function ajaxRequestor() { this.clearAll(); }

ajaxRequestor.prototype.__defaultError = function(sender)
{
var tempStr = "ajaxRequestor Error:\n" +
                  "status: " + this.requestor.status + "\n" +
          "headers: " + this.requestor.getAllResponseHeaders();
alert(tempStr);
}
ajaxRequestor.prototype.__defaultSuccess = function(sender)
{
alert("ajaxRequestor successfully returned from a request - but there is no handler assigned to receive it");
}
ajaxRequestor.prototype.__decodeString = function(inputStr)
{
var decoded = unescape(inputStr);
decoded = decoded.replace(/\%2F/g, "/");
decoded = decoded.replace(/\%3F/g, "?");
decoded = decoded.replace(/\%3D/g, "=");
decoded = decoded.replace(/\%26/g, "&");
decoded = decoded.replace(/\%40/g, "@");
return decoded;
}
ajaxRequestor.prototype.__encodeString = function(inputStr)
{
var encoded = escape(inputStr);
encoded = encoded.replace(/\//g,"%2F");
encoded = encoded.replace(/\?/g,"%3F");
encoded = encoded.replace(/=/g,"%3D");
encoded = encoded.replace(/&/g,"%26");
encoded = encoded.replace(/@/g,"%40");
return encoded;
}
ajaxRequestor.prototype.__getParams = function()
{
if (this.getNames.length == 0) { return ""; }
var out = (this.url.indexOf('?') == -1) ? '?' : '&';
for (var i=0; i<this.getNames.length; i++)
{
out += this.getNames[i] + '=' + this.getValues[i];
if (i < (this.getNames.length - 1)) { out += '&'; }
}
return out;
}
ajaxRequestor.prototype.__getRequestor = function()
{
if ((this.requestor != null) && (!this.reqIsIE)) { return true; }

try {
this.requestor = new XMLHttpRequest();
this.reqIsIE = false;
return; true;
} catch(e) {}

try {
this.requestor = new ActiveXObject("Msxml2.XMLHTTP.6.0");
this.reqIsIE = true;
return; true;
} catch(e) {}

try {
this.requestor = new ActiveXObject("Msxml2.XMLHTTP.3.0");
this.reqIsIE = true;
return; true;
} catch(e) {}

try {
this.requestor = new ActiveXObject("Msxml2.XMLHTTP");
this.reqIsIE = true;
return; true;
} catch(e) {}

try {
this.requestor = new ActiveXObject("Microsoft.XMLHTTP");
this.reqIsIE = true;
return; true;
} catch(e) {}

alert('ajaxRequestor Fatal Error: Cannot instantiate an XMLHTTP Object');
}
ajaxRequestor.prototype.__xmitLog = function(theMsg)
{
var bodyArr = document.getElementsByTagName('body');
var theBody = bodyArr[0];
theBody.appendChild(document.createTextNode(theMsg));
theBody.appendChild(document.createElement('br'));
}
ajaxRequestor.prototype.__onRTS = function()
{
if ((this.requestor.readyState >= 2) && (this.timeoutHandle))
{
clearTimeout(this.timeoutHandle);
this.timeoutHandle = false;
}

    if (this.requestor.readyState == 4)
{
if (this.masterStatus) { this.masterStatus.handleChange(false); }
if ((this.requestor.status==200) || (this.requestor.status==0))
{
this.lastResponse = this.__decodeString(this.requestor.responseText);
if (!this.lastResponse)
{
return false;
}
if (this.xmlHandler)
{
this.xmlHandler.importXML(this.lastResponse);
}
this.onSuccess(this);
} else {
switch(this.requestor.status)
{
case 12029:
case 12030:
case 12031:
case 12152:
case 12159:
alert('Untrapped error: ' + this.request.status);
/*
var loader = this;
setTimeout( function() { loader.execute.call(loader); }, 10);
*/
break;

default:
this.onError(this);
}
}
this.busy = false;
}
}
ajaxRequestor.prototype.__postParams = function()
{
var out = "";
var varNames = '';
for (var i=0; i<this.postNames.length; i++)
{
if (i > 0) { varNames += '|'; }
varNames += this.postNames[i];
if (i > 0) { out += '&'; }
out += this.postNames[i] + '=' + this.__encodeString(this.postValues[i]);
}
if (out) { out += '&' + 'ajax_var_names=' + varNames; }
return out;
}
ajaxRequestor.prototype.abort = function()
{
if (this.busy)
{
// clear timeout as well
this.requestor.abort();
clearTimeout(this.timeoutHandle);
this.timeoutHandle = false;
this.busy = false;
}
}

ajaxRequestor.prototype.clear = function()
{
this.methodPost = true;
this.__transStatus = 0;
this.__transBusy = false;
    this.lastResponse = new String();
this.selfReference = null;
    this.newRequest();
this.timeoutHandle = false;
this.timeoutMS = 5000;
}
ajaxRequestor.prototype.clearAll = function()
{
    this.xmlHandler = null;
    this.masterStatus = null;
    this.onUnrecognized = new String();

    this.onError = this.__defaultError;
    this.onSuccess = this.__defaultSuccess;
   
    this.clear();
}
ajaxRequestor.prototype.execute = function(timeoutVal)
{
if (this.busy)
{
// clear timeout as well
this.requestor.abort();
this.busy = false;
}

var thisTimeoutVal = this.timeoutMS;
if (timeoutVal != undefined) { thisTimeoutVal = timeoutVal; }

this.__getRequestor();

if (!this.requestor) {
alert("You cannot dispatch a request on this machine (no viable XMLHTTPRequestor)");
return "";
}
if (!this.url) {
alert("You must supply a URL to ajaxRequestor to process a request");
return "";
}

this.busy = true;
var httpMethod = (this.methodPost) ? 'POST' : 'GET';

var theURL = this.url;
theURL += this.__getParams();
this.lastRequest = theURL;

var loader = this;
this.requestor.onreadystatechange = function() { loader.__onRTS.call(loader); }
if (this.masterStatus) { this.masterStatus.handleChange(true); }

// Set a callback to <me> in case the request takes to long...
this.timeoutHandle = setTimeout( function() { loader.__handleTimeout.call(loader); }, this.timeoutMS);

this.requestor.open('POST', theURL, true);
this.requestor.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if ((document.all) && (document.getElementById))
{
// IE
setTimeout( function() { loader.__executeSend.call(loader) }, 10);
} else {
this.requestor.send(this.__postParams());
}
}
ajaxRequestor.prototype.__executeSend = function() { this.requestor.send(this.__postParams()); }

ajaxRequestor.prototype.__handleAbort = function()
{
if (this.masterStatus) { this.masterStatus.handleChange(false); }
this.requestor.abort();
}
ajaxRequestor.prototype.__handleTimeout = function()
{
this.__handleAbort();
var loader = this;
setTimeout(function() { loader.execute.call(loader); }, 100);
}
ajaxRequestor.prototype.getParam = function(key, value)
{
var ptr = this.getNames.length;
for (var i=0; i<this.getNames.length; i++)
{
if (this.getNames[i] == key) { ptr = i; }
}
this.getNames[ptr] = key;
this.getValues[ptr] = value;
}
ajaxRequestor.prototype.method = function(doPost)
{
this.methodPost = (doPost);
}
ajaxRequestor.prototype.newRequest = function()
{
this.getNames = new Array();
this.getValues = new Array();
this.postNames = new Array();
this.postValues = new Array();
this.url = '';
}
ajaxRequestor.prototype.postParam = function(key, value)
{
var ptr = this.postNames.length;
for (var i=0; i<this.postNames.length; i++)
{
if (this.postNames[i] == key) { ptr = i; }
}
this.postNames[ptr] = key;
this.postValues[ptr] = value;
}
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
jairez
Expert
****
Offline Offline

Posts: 164


JTFC


View Profile
« Reply #17 on: December 16, 2008, 11:44:20 PM »

BING!   "It used to be Bingo, but somebody stole all the O's.  Now we just play Bing." - overheard at retirement home

All right ... now I've got something I can tear apart and work with.

q: previously I had simply saved your class file - turns out, I only saved most of it   D'oh!- and named it myclass.js and included it in my .html file.  do I have to name it according to your example? 

I don't have a problem doing so, but I thought I understood this, but .....

I can't thank you enough for not only holding my hand here, but for also feeding me and shaking off my willy.  Sorry for all that, but again ... very VERY much appreciated.

     - ja

Logged

Spontaneity has it's time and place.  [Sluggo, 1990-ish]
perkiset
Olde World Hacker
Administrator
Lifer
*****
Online Online

Posts: 9792



View Profile
« Reply #18 on: December 17, 2008, 12:14:23 AM »

q: previously I had simply saved your class file - turns out, I only saved most of it   D'oh!- and named it myclass.js and included it in my .html file.  do I have to name it according to your example? 
Not have to but of course, it needs to be named something that makes sense to you and you call it from the HTML file.

...and shaking off my willy
Egads... WTF did I miss?  ROFLMAO
You realize of course, that PinkHat as well as your K will get pretty pissed off if that gets out...
« Last Edit: December 17, 2008, 12:18:01 AM by perkiset » Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
jairez
Expert
****
Offline Offline

Posts: 164


JTFC


View Profile
« Reply #19 on: December 17, 2008, 12:21:54 AM »

Quote
PinkHat as well as your K will get pretty pissed off if that gets out...

Maybe ... but Nuts will have a time with it, huh? 

Poor bastard.   ROFLMAO ROFLMAO
Logged

Spontaneity has it's time and place.  [Sluggo, 1990-ish]
nutballs
Administrator
Lifer
*****
Online Online

Posts: 5604


Back in my day we had 9 planets


View Profile
« Reply #20 on: December 17, 2008, 08:51:02 AM »

The only time I touched another man's penis was to save his life. And even then I hesitated.
 ROFLMAO
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Online Online

Posts: 9792



View Profile
« Reply #21 on: December 17, 2008, 09:06:37 AM »

Yeah, I saw you on YouTube, or perhaps it was on some nature site - "BearLove.com" or something.
Strangest form of CPR I've ever seen man.
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
nutballs
Administrator
Lifer
*****
Online Online

Posts: 5604


Back in my day we had 9 planets


View Profile
« Reply #22 on: December 17, 2008, 09:25:00 AM »

lol
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
jairez
Expert
****
Offline Offline

Posts: 164


JTFC


View Profile
« Reply #23 on: December 17, 2008, 10:03:15 AM »

JTFC --- that's some funny Shit!!!   

ROFLMAO ROFLMAO ROFLMAO
Logged

Spontaneity has it's time and place.  [Sluggo, 1990-ish]
Pages: 1 [2]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!