views:

121

answers:

1

I have a registration form with checking the available name for username field through ajax. Inputing a username into username field and pushing the "Check!" button, the script sends value to php script. Then php script replaces the username field with the username field + style like this:

alt text

So when replacing the username field in the form with its equivalent from php script and then submitting a form, it is then get to script on the page that checks whether the username field is empty or not. And it returns an error that it is empty, though after checking through ajax the username field it has value.

I don't understand why it gets to empty field checking script, having the same field name and having value?

P.S. In IE browser works well, but testing in Firefox and Opera returns an error!

This is a form like example:

<form method="post" action="check_form.php">
<div id="loadfield"><input type="text" name="username" value=""></div>
<input type="button" value="Check!" onclick="...script for sending username value to PHP script...">
<input type="submit" value="Submit a form">
</form>

This is a script, that checks for empty field after submiting a form:

<?
if(empty($_POST["username"])){
echo "<script>alert('Username field is empty!');</script>";
}
?>

This is a script, that AJAX send username for checking before submiting:

<?
if(empty($_GET["username"])){
echo '<input type="text" name="username" value="'.$_GET["username"].'" style="border-width:1; border-color:red; border-style:solid; background-color:rgb(255,232,230);">';
}
?>
A: 

Firstly, without seeing your Javascript code, it's hard to know what your script is doing with the response it's getting back from the HTTP request. I'd guess it's here that something's going wrong.

Secondly... I think that maybe you're approaching the problem the wrong way. What you're doing isn't really ajax at all. The conversation you're having appears to be:

js: Hi, please check this username for me
php: ok, here's a new input field to replace the old one with.

The conversation should be:

js: Hi, please check this username for me
php: Sorry, that username is taken
js: ok thanks, I'll let the user know

What your php script should return, is an XML file, indicating the availability of the username. Something like:

<?xml version="1.0" encoding="UTF-8"?>
<logincheck username="mylogin">
    <available>false</available>
</logincheck>

It's then up to your javascript code to interpret that response and add the classes to the input field (better than setting inline styles) or display any other message you think is appropriate.

Then you're actually doing ajax!

Orukusaki
I'm sending username via XMLHttpRequest() by GET method to php script. Then PHP checks the username var and form the response that ajax script then return like html with innerHTML back.
ilnur777