0

I'm using Ajax to check is if the fields in my registation form is valid or not.

My validate function:

<script type='text/javascript'>
    function validate(field, query) {
        xmlhttp = new XMLHttpRequest(); // Creating Object
        xmlhttp.onreadystatechange = function () // Checking if readyState changes
        {
            if (xmlhttp.readyState != 4 && xmlhttp.status == 200) // Validation Under Process 
            {
                document.getElementById(field).innerHTML = "Validating..";
            }
            else if (xmlhttp.readyState == 4 && xmlhttp.status == 200)  // Validation Completed
            {
                document.getElementById(field).innerHTML = xmlhttp.responseText;
            }
            else // If an error is encountered
            {
                document.getElementById(field).innerHTML = "Unknown Error Occurred. <a href='index.php'>Reload</a> the page.";
            }
        }
        xmlhttp.open("GET", "check.php?field=" + field + "&query=" + query, false);
        xmlhttp.send();
    }
</script>

And my check.php:

if ($field == "email") 
{
    $check = $db->prepare("SELECT * FROM users WHERE email = :query");
    $check->bindParam(':query', $query);
    $check->execute();
    $count = $check->rowCount();

    if ($count > 0)
    {
        echo "<script type='text/javascript'>document.getElementById('regr_btn').disabled = true;</script>";
        echo "<font color=red>Email already exists</font>";
    }
    else 
    {
        echo "<script type='text/javascript'>document.getElementById('regr_btn').disabled = false;</script>";
        echo "<font color=green>Email available</font>";
    }   
    if (!filter_var($query, FILTER_VALIDATE_EMAIL)) {
        echo "<font color=red><br />Please enter a valid Email</font>";
        echo "<script type='text/javascript'>document.getElementById('regr_btn').disabled = true;</script>";
    }
    else {
        echo "<script type='text/javascript'>document.getElementById('regr_btn').disabled = false;</script>";

My echo "<font color=red>Email already exists</font>"; work completely fine.

But as you can see, I also try to echo "<script type='text/javascript'>document.getElementById('regr_btn').disabled = false;</script>"; when an email already exist in my database.

But somehow it doesn't work. I also tried to display:none instead of disabeling my button, but still with no result.

If i put document.getElementById('regr_btn').disabled = true; into the console of google chrome, then it works fine. So somehow my javascript isn't called.

I hope that you can help me out.

hsz
  • 136,835
  • 55
  • 236
  • 297
  • If your scripts are not being accessed then there is probably an error causing this problem. Press the F12 key and select the console tab to view any errors. BTW, the element has been deprecated since HTML3 days. – jeff Jun 12 '14 at 10:01
  • Hi Jeff. Thanks for your comment. I don't have any errors in my console. –  Jun 12 '14 at 10:05
  • I dont think you can execute a script ajax responce by default. You need to edit your ajax request for this and use Jquery's getScript() function. But then you will loose your html responces. – andrew Jun 12 '14 at 10:09
  • Any reason you're not using jQueries `.ajax()`? Makes handling Ajax so much easier. – Styphon Jun 12 '14 at 10:09

2 Answers2

0

My suggestion is to use php only to return a response like: "Valid","Not valid", "Duplicate" and then in the javascript function executing the ajax call modify the DOM accordingly.

It is a nonsense (my opinion at least) to have php echoing some javascript.

Example:

if(data = "Valid") {
  $('#div_with_message').html('Email already exists');
}else{
  $('#reg_btn').attr('disabled',true);
}
Lelio Faieta
  • 5,913
  • 6
  • 34
  • 57
0

If I were you I'd switch to using jQuery and simply passing a response back, then dealing with the response in your page. A short example of how I would do it:

$.ajax({
    type: 'POST',
    url: '/path/to/php/file.php',
    data: {email: $('#email-field').val()},
    dataType: 'json',
    success: function(response) {
        if(response.count > 0) {
            $('#email-field-result').css('color', 'Red').text('E-mail already taken');
            $('#reg_btn').prop('disabled', true);
        } else {
            $('#email-field-result').css('color', 'Green').text('E-mail available');
            $('#reg_btn').prop('disabled', false);
        }
    }
});

And the PHP:

$query = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$check = $db->prepare("SELECT * FROM users WHERE email = :query");
$check->bindParam(':query', $query);
$check->execute();
$count = $check->rowCount();

$return = array(
    'count'    => $count
);
echo json_encode($return);

If you use JSON to return your response it allows you to pass back complex responses from your PHP script.

Styphon
  • 9,859
  • 8
  • 51
  • 82