2

I got a function in javascript that first checks if the username is the required length and than sends the username to a page for a test if the test is a success there will be a <span id="username">true</span> else <span id="username">false</span>

I keep getting an error that getElementById doesn't exist on the return data

  function checkuser(user, wd,id, sub)
    {
        if(user.length < 7)
        {
            document.getElementById(id).innerHTML = "Your username is too short. It must be longer than 6 charaters";
            document.getElementById(sub).disabled = true;
            return false;
        } else {
            $.post(wd + "register/checkuser/" + user,
                       function(data){
                         alert("Data Loaded: " + data.getElementById('username').innerHTML;
                       });
        }
    }
Ken
  • 2,654
  • 3
  • 26
  • 29

3 Answers3

4

The data return value is a string, not a DOMDocument - thus it doesn't have a getElementById member function.

A better idea would be to have your test page return JSON instead, and parse that.

If you can't change the page that does the testing/returning, then you'll need to find another way to parse the return string that serves your purposes.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • `data` isn't *always* a string, is it? It depends on the response's type and whether you've set `dataType`: http://api.jquery.com/jQuery.ajax/ It will be a string if the response is HTML, though, and JSON is absolutely the way to go for this kind of response. – T.J. Crowder Sep 12 '10 at 16:16
  • But either way, it's a string or json data, but still isn't in the DOM and won't have a getElementById() – Marc B Sep 12 '10 at 16:29
  • & Marc: I can't conveniently try it right now, but if you retrieve XML (or set `dataType`), don't you get a DOMDocument containing the XML document? (Attempts with JSBin failed, but that seems to be what the docs suggest.) Again, this is a side point, completely agree with Amber that JSON is the best way to go here. – T.J. Crowder Sep 12 '10 at 16:53
2

Try this:

   function(data){
       alert( "Data Loaded: " + $('#username', data).html() );
   });

Or this, depending on the structure of the HTML returned:

   function(data){
       alert( "Data Loaded: " + $(data).filter('#username').html() );
   });
user113716
  • 318,772
  • 63
  • 451
  • 440
1

You have to do this:

function checkuser(user, wd, id, sub) {
  if(user.length < 7) {
    $("#"+id).html("Your username is too short. It must be longer than 6 characters");
    $("#"+sub).attr("disabled", true);
    return false;
  }
  else {
    $.post(
      wd + "register/checkuser/" + user,
      function(data){
        alert("Data Loaded: " + $(data).find("#username").html());
      }
    );
  }
}
Flo Edelmann
  • 2,573
  • 1
  • 20
  • 33