How do you submit an ajax request every time the form input field changes?

For example, there is an input field. Each time a user enters a key in this field, he sends an AJAX request with any text at the moment and does something with it. I learned the change and keyup functions in jQuery, but when I try to use them in Jsfiddle, they do nothing. Is there a standard way to do this kind of operation? I know its general for validation and so on.

<form> <input id="test" type='text' > <input type="submit" value="asdf"> </form> $('input').on("change",(function(e){ alert("Hello"); }); 

The effect I'm going to is like this game www.sporcle.com/games/g/nflteams#

You can enter any text and, if it is within the set of correct answers, then the table will be updated to show this answer. You will never have to obey. Do you think that they have achieved this effect?

It seemed to me that they should query the database every time the user enters a key to make sure that this is the correct answer. If they update the table to display the answer. What are other ways to do this?

+4
source share
4 answers

sending a request with every change is just bad, ajax delay on the last change

 var changeTimer = false; $("your inputs").on("your change event",function(){ if(changeTimer !== false) clearTimeout(changeTimer); changeTimer = setTimeout(function(){ /* your ajax here */ changeTimer = false; },300); }); 
+12
source

I would probably do something similar to this. you will have to add additional code to handle the dropdown lists, but the idea is the same.

 $('form input').keyup(function () { $.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType }); }); 
+3
source

Just make a call to $.ajax() every time a change event is $.ajax() ! For instance:

 $(document).on('keydown','input',function(){ $.ajax({ // options here }); }); 

While the above will help you achieve what you want, I must inform you that you should not stop the constant AJAX requests, as this can lead to a huge load on the server if you have a lot of traffic. You would be better off either checking every n seconds, or checking the client side, or checking them when sending ...

UPDATE

It looks like you don't want to catch the change event that you would like to know when something is injected. As a result, I changed my code to catch the keydown event. This works whenever a key is pressed and focuses on the input.

+1
source
 $('#yourInputId').keyup (function () { $.post('http://yoururl.com', { value: $(this).val() }).done(function (data) { $('#feedbackDivId').html(data); }); }); 
+1
source

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


All Articles