After ajax success update input field and fire KeyUp event - javascript

I have an input field being dynamically updated from an AJAX function. How do I also fire a "keyup" even so the updated input value is picked up from another JS script. Basically I'm trying to mimic a user typing a number into the input field. Thanks in advance
Here is the code I have to update the input field
var interval = 500; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
$.ajax({
type: 'POST',
url: 'speed.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#kilometers').val(data);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
$('#kilometers').keyup(update);``

Related

How to Avoid Multiple Ajax calls

What I need
when click event is triggered service call is made then it may call only one time only.
Use case
Dropdown1
Dropdown2
Dropdown3
1. There are three dropdown in html page.
2. when dropdown 1 is call - ajax call made only 1 time.
3. when dropwdown 2 is call -ajax call made only 1 time.
4. when dropwdown 3 is call -ajax call made only 1 time.
Now user change dropdown 1.
5. when dropwdown 1 is call -ajax call made only 1 time.
Problem occurs
6. Now when dropwdown 2 is call -ajax call made only 2 time.
7. Now when dropwdown 3 is call -ajax call made only 2 time.
similary when we change dropdown 1
count increase by one.
Now user change dropdown 1.
8. Now when dropwdown 2 is call -ajax call made only 3 time.
9. Now when dropwdown 3 is call -ajax call made only 3 time.
Js code
dowpdown 1 has assigned id with dowpdown_1
dowpdown 2 has assigned id with dowpdown_2
dowpdown 3 has assigned id with dowpdown_3
$("#dowpdown_1").change(function() {
$.ajax({
url: 'path',
cache: false,
data: {
data
},
success: function(html) {
console.log('dowpdown_1');
$("#dowpdown_2").change(function() {
$.ajax({
url: 'path',
cache: false,
data: {
data
},
success: function(html) {
console.log('dowpdown_2');
}
});
}
$("#dowpdown_3").change(function() {
$.ajax({
url: 'path',
cache: false,
data: {
data
},
success: function(html) {
console.log('dowpdown_3');
}
});
});
}
});
});
Any solution is most welcome.
Everytime you change the dropdown_1 you are adding a new event to dropdown_2 and dropdown_3 that do the same thing.
It might seem that this is the same event but you are actually binding new change events to your dropdowns.
You can either bind only once the events or if you want your previous structure (seems like cascade functionality but I am not sure) you could use this:
$("#dowpdown_2").off().on('change', function () {// do the ajax});
$("#dowpdown_3").off().on('change', function () {// do the ajax});
This way everytime you add the new function on the change event you will at least unbind all previous events from it and it won't trigger again. Of course this means that there aren't any other change events that matter to your case because they will be unbinded too.
Else as I said you can just do this
$("#dowpdown_1").on('change', function ()
{
$.ajax({
url: 'path',
cache: false,
data: {data},
success: function (html)
{
console.log('dowpdown_1');
}
});
$("#dowpdown_2").on('change', function () {
$.ajax({
url: 'path',
cache: false,
data: {data},
success: function (html)
{
console.log('dowpdown_2');
}
});
$("#dowpdown_3").on('change', function () {
$.ajax({
url: 'path',
cache: false,
data: {data},
success: function (html)
{
console.log('dowpdown_3');
}
});
everytime your ajax is completed, your callback attaches a new event to your other 2 dropdowns. That means every time you bind an event inside of an ajax callback you have to care if an element exists or it will be new created.
TLDR adding .unbind in front of your event should fix this
$("#dowpdown_2").unbind().change(function () {
....
})

How to avoid ajax async when using jQuery events

I have an input field with ajax call (filling some other input fields) on blur and buttons with click events (some of the click events set input fields to an empty string).
For example,
$("#input_field1").on('blur', function () {
$.ajax({
//async:false,
method: "GET",
url: "my_ajax.php",
cache: false,
dataType: "json",
data: { data1: $("#input_field1").val()},
success: function(result){
$("#some_other_input").val(result.data2);
}
})
});
$("#button1").on('click', function () {
$("#input_field1").attr("readonly", true);
var form = $("#my_form");
form.validate().resetForm();
form[0].reset();//form contains #some_other_input
});
When that input field is focused and then user clicks on any button, blur event is triggered and of course, appropriate click event after it.
If I don't use async:false, ajax will fill those input fields after click event is processed and other inputs will be filled instead of being empty.
Reading about how async:false should be avoided always, I need a way for my click events to wait until ajax is done, if there is an ajax call at that moment.
You need a concurrency check for your cases. On your blur action; check and set a value to prevent reentering the other calls.
Also during an ajax request, you need to prevent clicking the buttons.
One more thing, what if just after bluring your input field, user re-focuses and re-focusouts your input? In this case, your action will be triggered twice.
As a result, you need to handle concurrency. There are also some javascript libraries to handle concurrency, you can either use them or handle by your own.
Anyway to handle your case, here is a sample code:
let hasCall = false;
$("#input_field1").on('blur', function () {
if(hasCall){
return; //there is an active call...
}else{
hasCall = true;
$("#button1").prop('disabled', true);//prevent clicking on button
}
$.ajax({
//async:false,
method: "GET",
url: "my_ajax.php",
cache: false,
dataType: "json",
data: { data1: $("#input_field1").val()},
success: function(result){
$("#some_other_input").val(result.data2);
}
}).always(()=>{
//reset the state:
hasCall=false;
$("#button1").prop('disabled', false);
});
});
$("#button1").on('click', function () {
$("#input_field1").attr("readonly", true);
var form = $("#my_form");
form.validate().resetForm();
form[0].reset();//form contains #some_other_input
});

Jquery for set timeout

I have an existing jquery code that calls for showing up div contents. Here is it:
$.ajax({
url: 'sendform.php?action=datapp',
type: 'POST',
data: data,
success: function (response) {
if (response == 'SUCCESS') {
$('#FormA').show();
$('#FormB').hide();
}
},
Now, I want to add a line here that starts a timer (timeout), which shows FormC after 20 seconds. Please help.
Try adding below script for showing Formc after 20 secon.
setTimeout(function(){ $('#FormC').show() }, 20000);

how to add delay function inside the ajax function

I am using ajax function to update and output the result.
how can I delay like 2 secs before the second update result get display again?
since right now, after the first update and second update, the text is the same like
'updated' I want to let user know this is the second time updated msg.
$.ajax({
type: "post",
url: "function.php",
data: "ajax=updateAward&" + inputs,
success: function(html) {
$('#message_award').html(''); //clear previous text
//delay 2 sec then display below?
$('#message_award').html(html) ;
}
});
Use setTimeout to execute a function after a delay (given in milliseconds). Here's a complete example:
$.ajax({
type: "post",
url: "function.php",
data: "ajax=updateAward&" + inputs,
success: function(html) {
setTimeout(function() {
$('#message_award').html(html);
}, 2000);
}
});

unbind event handlers while ajax in progress

I have a text field with keypress event handler jsfiddle. And when I type something in this field and press "Enter" 2 times, 2 requests will be send. I want to turn off all events, while ajax request in progress. One option is to call .off() function before ajax call, and then bind event handler again. Any other options?
use the callback handlers from your ajax call and a boolean used as flag. By setting the ajaxLoading boolean to false in the "always" callback, you can be sure that other, future requests can be made independent from whether the current ajax call throws an error or not.
var ajaxLoading = false;
if(!ajaxloading){
ajaxloading=true;
$.ajax({
url: 'your url',
type: 'GET',
dataType: 'JSON'
})
.done(function(data) {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
ajaxloading=false;
});
}
I use 2 boolean flags, like:
var is_requesting = false, should_request = false;
function onkeydown() {
if (is_requesting) {
should_request = true;
return;
}
is_requesting = true;
$.ajax({}, function () {
is_requesting = false;
if (should_request) {
onkeydown();
}
});
}
Is there a good reason for you not to use the jQuery .off() function?
If so then you could simply disable the control prior to making the ajax request and re-enable it once the request is complete. This would also stop the user from thinking he/she could change the result by changing the text value during the request.
//Disable the input
$('#myresult').prop('disabled', true);
$('#myresult').append('<br>'+$(this).val());
$.ajax({
type: "POST",
beforeSend: function() {},
complete: function() {
//Re-Enable the input
$('#myresult').prop('disabled', false);
},
url: "/echo/json/",
data: { delay : 3 },
success: function(){},
error: function() {},
dataType: 'json'
});

Categories