views:

79

answers:

3

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;
                       });
        }
    }
+4  A: 

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
`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
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
T.J. Crowder
+1  A: 

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());
      }
    );
  }
}
elektronikLexikon
thanks it worked
Ken
+2  A: 

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() );
   });
patrick dw
the first one worked perfectly thanks
Ken