How do you send an ajax request every time that a form input field changes?

前端 未结 4 1467
花落未央
花落未央 2021-02-09 05:34

For example, there is an input field. Every time a user types a key into that field, it sends an AJAX request with whatever text is currently in that input, and does something

相关标签:
4条回答
  • 2021-02-09 05:41

    I'd probably do something similar to this. you'd have to add some extra code to handle dropdowns, but the idea is the same.

    $('form input').keyup(function () {
        $.ajax({
          type: "POST",
          url: url,
          data: data,
          success: success,
          dataType: dataType
        });
    });
    
    0 讨论(0)
  • 2021-02-09 06:03

    sending a request on each change is just bad, delay the ajax 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);
    });
    
    0 讨论(0)
  • 2021-02-09 06:03

    Just make an $.ajax() call every time the change event is fired! Like so:

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

    Whilst the above will help achieve what you want, I must advise that it is not great practice to fire off constant AJAX requests as this can put a huge load on the server if you have a lot of traffic. You would be better off either validating every n seconds, or validating client side, or validating on submission...

    UPDATE

    It appears you do not want to catch the change event, you would like to know when anything is entered. Resultantly, I have changed my code to catch the keydown event. This will fire whenever a key is pressed down whilst focused on an input.

    0 讨论(0)
  • 2021-02-09 06:07
    $('#yourInputId').keyup (function () {
        $.post('http://yoururl.com', { value: $(this).val() }).done(function (data) {
            $('#feedbackDivId').html(data);
        });
    });
    
    0 讨论(0)
提交回复
热议问题