简体   繁体   中英

AJAX calls only working once

Here's my code:

<script type="text/javascript">
    $(document).ready(function() {
      $('#username').change(check_username);
    });

    function check_username() {
      $("#check_username").html('<img src="images/site/ajax-loader.gif" />username avilable??').delay(5000);
      var usernametotest = $('#username').val();    
      $.post("backend/username_available.php", { username: usernametotest})
       .done(function(data) {
         $("#check_username").replaceWith(data);
       });
    }
</script>

I use this code for checking with AJACX the availability of a username in my form. It works perfect but just once. When an username is occupied and I change the username, no AJAX checks are done after the first one? The text "username already exists" (in the variable data), is not replaced by "username ok".

This JavaScript is added just before the </html> tag.

Your code looks fine - see this jsfiddle with an alert on the usernametotest value for more visibility

$(document).ready(function() {
    $('#username').change(check_username);
});

function check_username(){

    $("#check_username").html('username avilable??').delay(5000);
    var usernametotest = $('#username').val();

    alert('posting username ' + usernametotest);

    $.post("backend/username_available.php", { username: usernametotest} )
        .done(function(data) {
            $("#check_username").replaceWith( data );
        });  
}

The post requests are being made every time with the correct payload, so no problems there (check browser developer tools eg Network tab / XHR in Chrome)

Must be an issue with the response coming back from backend/username_available.php ? Check the response of the first request vs the rest, and the difference and hence the problem will probably jump out at you.

Whenever you replace an element ... and here you do just that...

$("#check_username").replaceWith( data );

all those element's handlers are lost . So change() no longer works. To be able to use it again, you just need to bind again the element after it has been rewritten:

$('#username').change(check_username);

Or bind the handler to a parent and delegate it:

$('#username').parent().on('click', '#username', check_username);

(I feel that a class selector would work better - call it superstition on my part)

You could try this:

$('#username').on('change', function() {

  // write your code here

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM