Is there any danger of speedly repeating an ajax procedure? - javascript

$('#gd').on('click', function(){
// move up and down DOM elements
// some ajax procedure to store new values on database (php/mysql)
});
Is there any danger to repeating this click very quickly for a long time?
For example - if the connection is poor - will the ajax will not complete each time?
I tested on my live server - seems there is no problem, but... I'm still concerned.
And what is the way to avoid possible problems it this scenario - i.e. if a user keeps clicking very quickly on the #gd button.

This "Danger" would be more accurately described as undesired behavior. However, it is indeed issue which should be treated - as sending multiple request when only 1 is required would consume resources on both client and server with no reason.
If you would like to prevent the user from clicking the button while the request is being processed, disable the button after the client send it it, and re-enable it after response processing complete:
$('#gd').on('click', function(){
// 1. do some stuff with DOM
// 2. disable button + make ajax call
$.ajax({someRequestOptions})
.always(function() {
// 3. re-enable button
});
});

Related

How to handle multiple requests being sent in JavaScript?

Working on a platform, to enable auto-ticketing functionality. For which a REST API request is used for ticket creation. Unfortunately, there are 2 requests popping simultaneously, which results in creating duplicated tickets.
How to handle such case and send only one of these requests?
Tried adding the 2nd request in the response callback of the first, though this does not seem to work.
if (flag == 1){
logger.debug("Node-down alarm-Request raised - +sitn_id);
clearTimeout(mouseoverTimer);
mouseoverTimer = setTimeout(function(){
logger.debug("Inside Call back function - ");
//function call for ticket creation
incidentRequest(sitn_id,confUtil.config.mule_url);
}, 10);
You really should show more of the code that makes the request, though it seems as if you are doing some ajax inside your 'incidentRequest', so I will presume that (if that isn't what you are doing, then please, show your code....) - and since you tags say javascript and jquery - well, here goes...
To stop the 'double send' in an AJAX call, it is simple:
function incidentRequest(sitn_id,confUtil.config.mule_url){
// stop the double by clearing the cache
$.ajaxSetup({cache: false});
// continue on with the AJAX call
// presuming the url you want is confUtil.config.mule_url
// and the data you want to send is sitn_id
$.post(confUtil.config.mule_url, 'sitn_id=' + sitn_id, function (data) {
// do cool stuff
});
}
Hopefully that will help you get moving. If not, then we will need more code of what is going on around all this.

sending ajax request but not getting right result.Js

i am trying to display the data fetched from database in the loop and between loop i call the function and send ajax request its not working.Actually its displays the only if i used alert command. If i used alert then the browser display the div and then alert if i clicked ok then it displays the second div then again show alert.
Here is the js code
function like(divid,id,session) {
var orgnldiv=document.getElementById(divid);
var ndiv=document.createElement('DIV');
var idd=id+5000;
ndiv.id =idd;
ndiv.className="likeclass";
orgnldiv.appendChild(ndiv);
var dynamicdiv=document.getElementById(idd);
var span=document.createElement('span');
var spanid=idd+5000;
span.id=spanid;
span.className="spanclass";
dynamicdiv.appendChild(span);
var xmllhttp15;
if (window.XMLHttpRequest) {
xmlhttp15=new XMLHttpRequest();
} else {
xmlhttp15=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp15.onreadystatechange = function() {
if (xmlhttp15.readyState==4 && xmlhttp15.status==200) {
document.getElementById(spanid).innerHTML=xmlhttp15.responseText;
}
}
xmlhttp15.open("GET","spancount.php?postid="+id+"&userid="+session);
xmlhttp15.send();
// alert(spanid);
}
please suggest me what can be the reason of this problem my code is working well only if i use alert
The reason why your code works when you use alert is because whenever the alert function is called. The program flow is paused. In other words, your loop wont continue to make another Ajax call until you dismiss the alert.As a result, the request gets handled properly and the response data appears in the span div. that is why I had mentioned to make your calls synchronous instead.
So to answer the question you asked in the comment, Yes at times too many Ajax calls can be a problem. Let's say that the loops runs more than 15-20 times, that means 15-20 simultaneous requests. Now, think about the number of times the same request is being handled by the php script? Definitely a problem here!
Even with Jquery Ajax, the chances of the loop completing successfully is also 50-50 actually because it all boils down to the amount of requests being made , the bandwidth being used and how the request is being processed at the server.
One possible way to fix this problem is : Rather than constantly requesting small peices of data again and again from the server in the loop, Make one Ajax call and get the entire data as json. Then, parse the json and append data to the spans by using the particular span id to extract the relevant data from the json object.
You might have to do a little bit of tweaking in both the above javascript and spancount.php . But it will definitely Save you A LOT of bandwidth. You gotta consider the fact that more than one person could be using your site!!
Hope that cleared up things, all the best with your project :D

jQuery Ajax, prevent the refresh button when the ajax is in progress

Hi i have to perform perform like, when the ajax is in progress, then do not allow the user to do page refresh.
here is the code i have
$('#submit').click(function() {
$(function() {
$(".col1").mask("Generating csv...."); //This will generate a mark, Here i would like to prevent the user from doing any sort of operation.
var to = $('#filters_date_to').val();
var from = $('#filters_date_from').val();
$.ajax({
url:"../dailyTrade/createCsv?filters[date][to]="+to+"&filters[date][from]="+from,success:function(result){
if(result) {
$(".col1").unmask(); //Here we can unlock the user from using the refresh button.
window.location = '../dailyTrade/forceDownload?file='+result;
setTimeout('location.reload(true);',5000);
}
}
});
});
});
Any suggestions.
Best you can do is use onbeforeunload to present the user with a message saying that a request is in progress and asking them if they are sure they want to proceed.
e.g.
var req;
window.onbeforeunload = function() {
if(req) {
return 'Request in progress....are you sure you want to continue?';
}
};
//at some point in your code
req = //your request...
You cannot, in any way, prevent the user from leaving your page using JS or anything else.
I doubt if you should do that.
$(window).bind('beforeunload',function(){
return 'are you sure you want to leave?';
});
If you are talking about a refresh "html button" on your web page, that can easily be done. Just before you make your ajax call, disable your refresh button and on success/error function of the ajax call enable it.
Disable button
$("#refreshBtn").attr("disabled", "disabled");
Enable button
$("#refreshBtn").removeAttr("disabled");
You cannot do it just by inserting JavaScript code.
Only ways I can think of are:
Use synchronous ajax call, on that way browser should freeze (however it will notify user that script is taking too long to process and user will be able to stop execution)
Write browser plugin that will modify browser behavior (eg. prevent refreshing page for url that you preset)
Both ways are ugly and I wouldn't recommend doing it.
You should modify your script so it can resume execution if page has been refreshed (use HTML5 localStorage).
http://www.w3schools.com/html/html5_webstorage.asp
In your case, I would put in localStorage simple state (boolean) to check did ajax call happened or not. If it did happened, then just try calling again same url and you will get file name. But on server side (if you haven't done already) you should implement caching, so when same url is called twice, you don't need to make two separate files, it could be same file (server will be much lighter on hardware resources).

Saving data form without button

What is a good way of saving data form without submit button?
I have one idea. Below exemplary source code.
var delay = 1000,
timeId,
ajax,
//fw is some framework
form = fw.get('myform');
form.getFields().on('change', changeEventHandler);
function changeEventHandler() {
clearTimeout(timeId);
timeId = setTimeout(this.ajaxRequest, delay);
}
function ajaxRequest() {
//What do with old ajax request? Abort it?
ajax = fw.ajax({
url: 'ololo',
params: {
data: form.getValues()
}
});
}
What do with old ajax request? Abort it?
Have somebody other ideas?
I had a similar problem when designed an interactive form without save button.
First of all, its not a good idea to save the data on every change. I used on blur event, so when the input loses focus, I check if the value was changed (i.e. not just focus-blur on the input), if it was changed, I disabled the input and send an ajax request. When the request returned, I enabled the input once again (possibly displaying an error if the ajax failed and etc, depends on your needs).
Its the easiest way to do interactive form. This avoids the headache of multiple request trying to modify the same value on server side and the headache of monitoring all ajax requests.

Requesting something via ajax - how to stop other requests until this one is done

I have a php script that outputs json data. For the purposes of testing, i've put sleep(2) at the start.
I have a html page that requests that data when you click a button, and does $('.dataarea').append(data.html)
(php script returns a json encoded array. data.html has the html that i want to put at the end of <div class="dataarea">...HERE</div>.
The trouble is, if i click the button too fast (ie. more than once within two seconds (due to the sleep(2) in the php script)), it requests the php file again.
how can i make it only do one request at a time?
i've tried this (edited down to show the important parts):
amibusy=false;
$('#next').click('get_next');
function get_next() {
if (amibusy) {
alert('requesting already');
}
else {
amibusy=true;
// do the request, then do the append()
amibusy=false;
}
}
but this doesn't seem to work. i've even tried replacing the amibusy=true|false, with set_busy(), and set_not_busy(). (and made a function am_i_busy() { return amibusy; })
but none of this seems to work. what am i missing?
If you're in jQuery the amibusy would be jQuery.active which contains a count of currently active AJAX requests, like this:
if(jQuery.active > 0) { //or $.active
alert('Request in Progress');
}
Keep in mind that in jQuery 1.4.3 this becomes jQuery.ajax.active.
Disable the button in the click event and enable it again when the request is finished. Note that the request is asynchronous (i.e. "send request" returns immediately), so you must register a function that is called when the answer comes in.
In jQuery, see the load() function and the success method plus the various AJAX events which you can tap into with ajax().
I'm wondering about your "do request" logic. Whenever I've done calls like this they've always been asynchronous meaning I fire the request off and then when the response comes another function handles that. In this case it would finish going through that function after setting the callback handler and set your value of amibusy back to false again before the request actually comes back. You'd need to set that variable in the handler for your post callback.
Could you use the async variable?
http://api.jquery.com/jQuery.ajax/
asyncBoolean Default: true
By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to false.
Cross-domain requests and dataType:
"jsonp" requests do not support
synchronous operation. Note that
synchronous requests may temporarily
lock the browser, disabling any
actions while the request is active.

Categories

Resources