Page 1 of 1

an issue with js split() function

Posted: Wed Aug 17, 2011 1:56 am
by Ark
Hey guys just got a problem with split() function, probably i'm using incorrectly. here's the code:

function updatestats()
{
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var stats = ajaxRequest.responseText.split("/");//for ex the responsetext is:"hello/how/are/you"
alert(stats[0]);

}
}
ajaxRequest.open("GET", "getinfo.php?p1="+p1+"&p2="+p2, true);
ajaxRequest.send(null);
}

Probably by watching halls AJAX tuts, stats[0] will be "hello" and stats[1] is:"how" but all what the alert returns is:"<!DOCTYPE html PUBLIC "-"
Please someone tell my what i'd wrong and a way to fix it.

Re: an issue with js split() function

Posted: Wed Aug 17, 2011 1:59 am
by Ark
this should be on beginner help and support sorry xD

Re: an issue with js split() function

Posted: Wed Aug 17, 2011 3:22 am
by SpiritWebb
Moved to beginner help and support

Re: an issue with js split() function

Posted: Thu Sep 08, 2011 7:44 pm
by Chris
Can you make sure that responseText is really what you think it is. This should work.

I remember having some problems like this way back, just can't remember what the solution was. I use jQuery for everything now :P

And by the way, if you're looking to pass an array from PHP to JavaScript you might want to look into JSON:

http://php.net/json_encode
http://php.net/json_decode

http://json.org/
http://www.json.org/js.html

Re: an issue with js split() function

Posted: Thu Sep 08, 2011 7:54 pm
by Jackolantern
I would highly suggest using jQuery. As your AJAX calls stand now, you basically have no error-handling, or any handling of other response codes. Every time you use the simple 1-line AJAX calls in jQuery, you are getting the benefit of hundreds of lines of response code handling, error handling, latency balancing, etc. It makes your code much more robust.

And here is how you can manually format JSON objects in PHP to be sent back for easy consumption in Javascript:

Code: Select all

echo '{ "monsterDmg": "'.$monsterDmg.'", "playerDmg":"'.$playerDmg.'", "playerHP":"'.$playerNewHp.'", "mobHP":"'.$mobNewHp.'", "mobName":"'.$mnName.'" }';
It took me a while to get that all worked out right lol, and I use it as a template all the time now.