Question

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;
                       });
        }
    }
Was it helpful?

Solution

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());
      }
    );
  }
}

OTHER TIPS

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.

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() );
   });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top