Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

What format does responseText return?

Hi Guys

Not entirely sure whether the above question is accurate but in short when I get a returned value from responseText (using xmlhttprequest), I can use the returned value to store in divs or alert's...

However if I try to use anything like charAt() etc on the value.....it doesn't work....Do I have to turn it back to a string somehow?

Does anyone know why? Is it something to do with parsing? For instance I have to use parseInt(myvariablename) on occasions.

I fix it by putting the value into a div...then storing that value into a variable referencing innerText.....but this seems such a poor way of sorting an issue.

Any tips? (if anyone is kind enough to respond...please no frameworks, i.e jquery solutions).

Dave McFarland
Dave McFarland
Treehouse Teacher

Can you show your code? What happens if you console out the typeof responseText in the onreadystatechange like this:

xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            console.log(typeof xmlhttp.responseText);
        }
    }

8 Answers

Hi Dave,

Thanks for the response.

I did the console log to which the result is in fact string.

What's the best way for me to attach my code on Treehouse? I'm working from localhost so there isn't a web/live version.

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

It the type is a sting, then charAt() should work. I just ran a test and this line of code console.log(xmlhttp.responseText.charAt(0)); did return the first letter of the string.

What happens when you use charAt()? Do you get an error message? Can you paste the code you're using to access charAt() that might help me figure this out.

My console log is now blank :/

Code below

Function ajaxreq(){

if(window.XMLHttpRequest){

    var xhr = new XMLHttpRequest();

}else{

  var xhr = new ActiveXObject('Microsoft.XMLHTTP');

}

     var url = myphpfile.php
     var myvar = "1";

     var vars = "myvar="+myvar;
     vhr.open("POST", url, true);

     vhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

     vhr.onreadystatechange = function(){

      if(vhr.readyState == 4 && vhr.status == 200){

         var returned_string = vhr.responseText;
         console.log(returned_string.charAt(0));

          }


      }

     vhr.send(vars);
     document.getElementById('mydiv').innerHTML = 'LOADING...';

}

console returns blank. Php file is echoing both numbers and text....

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

I see one problem in your code:

var url=myphpfile.php

You need to put myphpfile.php in quotes:

var url = 'myphpfile.php';

That may be the problem. If not: What happens if you add console.log(returned_string) after var returned_string = vhr.responseText;? Is anything printed to the console?

Have you tried Chrome's Web Dev Tools to debug? This video shows you how you can check responses for Ajax calls: https://www.youtube.com/watch?v=WOQDrGrd9H8

Sorry that was a typo...in my code the vars= "myphpfile.php" is in quotes.

Adding console.log before the variable is declared, returns undefined as expected. However console.log(returned_string) after the variable is declared, does in fact return the whole string.....which is most likely why I can add it to divs...alerts etc

The moment I try then to use it in any way i.e charAt() is when it returns a complete blank.....

So it knows it is defined.....to which is why I was surprised when it acknowledges it as a string, as it doesn't seem to want to treat it like one.

I read somewhere that responseText, returns text....so you can't use it...and you need to use JSON or something :s.....if so, I'l stick with passing it through a div and assigning the div's innerHTML to a var....it's two lines of code, just seems like such a poor solution.

I am using google dev tools...in regards to the link you sent....what would I be looking for? It has sent the string.....

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Rich,

Without seeing the code or output I can't really say what's going wrong. Here's one idea: you are trying to get the first character of responseText with charAt(0). What is the first character returned? If it's a space or control character you might not see anything. Try a different value like charAt(19) and what happens?

You can also try casting the response as a string:

var returned_string = String(vhr.responseText);

This will force the responseText to be converted into a JavaScript string type. (This is just a wild shot in the dark, however. It really shouldn't be needed)

Right I think I've got it

I put the variable into an object like this

var newstring = new String(returned_string);

console.log(newstring);

it returned my string in a huge list to which the first few were blank

0 = ' ' ; 1 = ' ' ;

until about the 4th one down which using charAt(4) allows me to access the first part of my string.

So, here is a new question....what are the first few array elements of the array :/

Obviously I could just push my char.At(0) to char.At(4) to get the first one.....or use regex to eliminate the blank ones.....but my original solution with the divs seems quicker.

Interested to have your thoughts.

Dave McFarland
Dave McFarland
Treehouse Teacher

Those empty characters are happening on the server side -- the script is injecting them or the web server somehow. It's not usual that extra characters are just added to an XMLHttp request. I'd look at the server script to see how to modify it.

Dave McFarland
Dave McFarland
Treehouse Teacher

You could also use the JavaScript trim() function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Works in all browsers except IE8 and earlier :(

Right, well that's interesting to know then.

In regards to the div method.....is there any cons in using this? Just thinking about saving time as my project is pretty far behind and lots still left to do.

Just tried posting a new php variable and it still gave a gap of 5 array elements....I'l take a look at the php script in detail to see if anything else is being echoed :/ , wouldn't have thought so.