Angel Miladinov
Angel Miladinov

Reputation: 1655

On key up or change event, fire Ajax to send data in jQuery

I've tried both keyup and change functions and here's why they don't do the trick. The user enters a voucher code and I want to send and ajax request which checks if the voucher exists in the database. I've tried:

$('#discount-voucher').keyup(function(event) {
    // Get the value
    let value = $(this).val()

    // Check if exists
    $.ajax({
        url: '{{ route('get-voucher') }}',
        type: 'POST',
        data: {_token: '{{ csrf_token() }}', code: value}
    })
    .done(function(data) {
        if (data == 'error') {
            $('span#voucher-error').text('Неавлиден ваучер')
        }
    })
    .fail(function() {
        console.log("error")
    })
    .always(function() {
        console.log("complete")
    })
})

But those vouchers will be sent by email and let's say the user copy paste them. It will not work. And with the change function the user has to click outside of the input or to press enter for the function to take effect and I don't want that neither I want a tip/hint which says "click outside the input ot press enter to check if the voucher is valid". So the things I need is something like the change function which takes effect without clicking or pressing enter

Upvotes: 4

Views: 2524

Answers (1)

john Smith
john Smith

Reputation: 17906

There is a paste event, you can set multiple eventlisteners like following:

$('#discount-voucher').on('keyup paste change', function () {
      //Do something  . . . .
});

also you may need to throttle the ajax request so it doesn't get called too often by typing.

Upvotes: 8

Related Questions