$ (this) .attr ("name") does not work with $ .post

I use this code in a simple way. Please 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 is it 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; }; }); }); }); 

This is a very strange thing !!

+4
source share
3 answers

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); }); //console.log(el.attr("name"), el.val()); this.lastValue = this.value; }; }); }); }); 

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.

+6
source

Instead

  $.post("ajax-validation.php", { $(this).attr("name") : $(this).val() }, 

Try

  var hash = {}; hash[$(this).attr("name")] = $(this).val(); $.post("ajax-validation.php", hash, 
+2
source

$ (this) .attr ("name") is an object, not a string that you expect to provide in your message. try $ (this) .attr ("name"). value or $ (this) .attr ("name"). val (), I don’t remember which one should work for you.

-3
source

Source: https://habr.com/ru/post/1384334/


All Articles