carlgcode
carlgcode

Reputation: 255

JavaScript and function variables

Let us say I have this on a html form...

<input id="world" type="text" onblur="return hello ('world');" />

And in my script I have

function hello (id) {
      document.write(id);
}

It returns world as expected. If I use it like this though...

function hello (id) {
      var val = $('#' + id).val();
      $.post("ajax.php", {
          id: val,
      });
}

Then the id returns Array, how can I make it return username like I want it to.

Thanks.

As requested the php side of things...

if (isset($_REQUEST['username'])) {
    $q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
    $q -> execute(array($_REQUEST['username']));

    if (strlen($_REQUEST['username']) < 3) {
        echo '<div class="error">Has to be at least 3 characters</div>';
    }   
    elseif ($q -> rowCount() > 0) {
        echo '<div class="error">Username already taken</div>';
    }
    else {
         echo '<div class="success">Username available</div>';
    }
}
else {
    echo $_REQUEST;
}

If it should equals username like it should do then the ajax is successfull else it will echo the result of $_REQUEST which is at the moment Array.

UPDATE

Calling the function:

<input id="world" type="text" onblur="return ajax ('username');" />

The original function:

function ajax (id) {

var val = $('#' + id).val();

$('.loading').fadeIn().delay(100);

$.post("ajax.php", {id: val};

}

I did a var dump on the Array and it returns the string that was entered into the textfield?? Not the id that I passed to the function?!? Why is this happening?

Example of var_dump($_REQUEST)

array
 'id' => string 'dadadas' (length=7)

Upvotes: 1

Views: 101

Answers (2)

Dennis
Dennis

Reputation: 32608

Your PHP code is checking for username:

if (isset($_REQUEST['username'])) {

Change your code to provide username instead of id

function hello (id) {
    var val = $('#' + id).val();
    $.post("ajax.php", {
        username: val
    });
}

$_REQUEST is an array, which you are echoing because the request parameter username is not being found.

Upvotes: 2

Pointy
Pointy

Reputation: 413826

You've probably got more than one element on the page with the same "id" value. That's not valid markup, as "id" values must be unique across the entire page.

edit — re-using "id" values is indeed a bad idea, but it wouldn't cause that behavior. I suspect there may be other code involved that would explain more. I'll leave this answer here but nobody should vote for it :-)

Upvotes: 0

Related Questions