I’m using this code on a simple form. Please can you tell me why this code works
$(document).ready(function(){
$(":input").focus(function() {
$(this).keyup(function(){
if (this.value != this.lastValue) {
$.post("ajax-validation.php", { "username" : $(this).val() },
function(data){
$("#display").html(data);
});
this.lastValue = this.value;
};
});
});
});
and this not?
$(document).ready(function(){
$(":input").focus(function() {
$(this).keyup(function(){
if (this.value != this.lastValue) {
$.post("ajax-validation.php", { $(this).attr("name") : $(this).val() },
function(data){
$("#display").html(data);
});
this.lastValue = this.value;
};
});
});
});
It’s a very strange thing!!
It’s not.
$(this)has no context where you put it. You need to cache it and reuse it. Like so:CODE CORRECTED! It appears that the use of methods (even if it returns a string) is not allowed. So I put it in another variable and used it there. Tested and works. (see the requests with dev tools or firebug)
CODE CORRECTED! AGAIN! It appears as though
$.postdoesn’t like variables (it treats them as strings), so I define the data object outside the$.postmethod, and pass it in. Works like a charm.Important points to consider
The code is correct but not robust, meaning, it will work exactly as you asked in the answer, but it might, and it will choke your server with endless requests in case of an attack. You should:
setTimeoutto throttle the requests (only after 3-4 seconds with no editing).You should, (in my opinion) have a validate button (or link, or whatever) to check whether the input is valid, rather then automatically validating on keypress.