onchange不会打印出空输入的错误

I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.

For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.

Here's the php part:

if(isset($_GET["isbn"]) )
{
    $isbn = $_GET["isbn"];

    $error="";

    if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
    {
        $error .= "Please enter a valid ISBN";
        echo $error;
    }
    else
        echo $error;

}

Here's the rest:

<script type="text/javascript">                         
    function validateIsbn(keyword)
    {
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {

            if(xhr.status == 200 && xhr.readyState == 4)
            {
                var res = xhr.responseText;
                document.getElementById("err1").innerHTML = res;
            }
        }

        xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
        xhr.send();
    }

    </script>

<form method="get" action="">


            <label class="top-label">ISBN:</label>
            <input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
            <div id="err1"> </div>
            <p></p><p></p>

You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.