This is not true. $(this)
has no context where you put it. You need to cache it and reuse it. For instance:
$(document).ready(function() { $(":input").focus(function() { $(this).keyup(function() { var el = $(this), theName = el.attr("name"), data = {}; data[theName] = el.val(); if (this.value != this.lastValue) { $.post("ajax-validation.php", data , function(data) { $("#display").html(data); });
CODE FIXED! It seems that using methods (even if it returns a string) is not allowed. So I put it in another variable and used it there. Tested and working. (see queries using dev or firebug tools)
CODE FIXED! AGAIN! It seems that $.post
does not like variables (it treats them as strings), so I define a data object outside the $.post
method and pass it. It works like a charm.
Important points to consider
The code is correct , but not reliable , that is, it will work exactly as you requested in the answer, but it can also be a server with endless requests in case of an attack. You must:
- Create a timer (with
setTimeout
to throttle requests (only after 3-4 seconds without editing). - Make sure that you are secure on the server side, do not allow many requests of the same connection. Use the connection information in conjunction with a global counter (stored in a database or text file) to determine if the user is abusing your system and blocking it.
You should (in my opinion) have a confirmation button (or a link or something else) to check if the input is valid, and not automatically check the keystroke.
source share