call another ajax function recursively from ajax success - javascript

I have a web page that is used to request the reports. When the user clicks a button, I am calling a function that will make a ajax request to process the reports. Once the request is made, I am using setInterval function to check the status of the report (whether is completed or not) every 1 second. Some how, the function inside setInterval() is not called at all.
Following is the javascript code that I have
var GLFiles_JSObject = {
url: "<%= Request.ApplicationPath %>/AjaxRequest.aspx",
apppath: '<%= Request.ApplicationPath %>',
btnRefreshId: '<%= btnRefresh.ClientID %>',
ajaxFunctionName: 'GLBuilder_ReprocessFiles',
reportstatusFuncName: 'GLBuilder_GetReportStatus',
reportid: 0,
ajaxError: function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest.statusText);
},
ajaxSuccess: function(msg) {
if (msg === '') {
setInterval(function(){
this.reportstatus();
}, 1000);
}
},
reportstatusSuccess : function(msg) {
if (msg === '1') {
clearInterval();
}
},
reportstatus : function() {
var keys = new Array('reportid');
var values = new Array(reportid);
//ajax call
WebServicePost(true, this.url, this.reportstatusFuncName, keys, values, this.ajaxError, this.reportstatusSuccess);
}
};
//this will be called when button is clicked.
function reprocessGLFiles(reportid, btnid) {
//disable the button
//$('#' + btnid).attr("disabled", true);
GLFiles_JSObject.reportid = reportid;
var keys = new Array('reportid');
var values = new Array(GLFiles_JSObject.reportid);
// make an ajax request to process the files
WebServicePost(true, GLFiles_JSObject.url, GLFiles_JSObject.ajaxFunctionName, keys, values, GLFiles_JSObject.ajaxError, GLFiles_JSObject.ajaxSuccess);
return false;
}

The reason it is not being called is probably because you using the this var which means something else. If you change this.reportstatus(); to GLFiles_JSObject.reportstatus() will probably fix your problem.
On a different note, I think you are misunderstanding something here. Why do you need to call a timer method for this to check status. OnSuccess is called when the method the ajax request is finished. So you don't need to call setTimeout.

Related

Show ajax process 1 by 1 when something is done

I have a code and it works, and it shows all notifications at the same time.
I have question..
How to get notifications when one of the functions is done? (Notifications appear one by one)
There are several functions in the indexing.php file.
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
buatindex();
hitungbobot();
panjangvektor();
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
In index.php there is a code to call that function
<script type="text/javascript">
function preproses(){
var preprosesx = "preproses";
$.ajax({
type : "POST",
url : "indexing.php",
data: {preproses:preprosesx},
error: function(){
$("#notif").prepend("fail");
},
success: function(html){
$("#notif").prepend("Process done <br/>"+html);
},
});
return false;
}
</script>
click to precess
If all processes are completed, a notification will appear
<span id="notif"></span>
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
setTimeout(function(){ buatindex() }, 3000);
setTimeout(function(){ hitungbobot() }, 3000);
setTimeout(function(){ panjangvektor() }, 3000);
console.log("Completed all");
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
Also you can console.log in ajax success response.
Something Like this : JsFiddle Example
count your post parameter ($_POST["preproses"]) and keep into an javascript variable like var count = ""; . you can also take an hidden text variable which will be increase by 1 after every notification send. after all notification values send this hidden variable will be equal to the count variable. then you can be sure that all the notifications have been sent. Hope this will work for you..:)
Haven't you tried async: false yet? This will stop further processing until one ajax request is complete.

Cancelling AJAX request if previous AJAX response hasn't been received [duplicate]

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort().
See the documentation:
abort Method (MSDN). Cancels the current HTTP request.
abort() (MDN). If the request has been sent already, this method will abort the request.
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
UPDATE:
As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).
UPDATE 2:
As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr any more. See the 3.0 blog here.
UPDATE 3: xhr.abort() still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.
You can't recall the request but you can set a timeout value after which the response will be ignored. See this page for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request.
You can also use the abort() method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.
Save the calls you make in an array, then call xhr.abort() on each.
HUGE CAVEAT: You can abort a request, but that's only the client side. The server side could still be processing the request. If you are using something like PHP or ASP with session data, the session data is locked until the ajax has finished. So, to allow the user to continue browsing the website, you have to call session_write_close(). This saves the session and unlocks it so that other pages waiting to continue will proceed. Without this, several pages can be waiting for the lock to be removed.
It's an asynchronous request, meaning once it's sent it's out there.
In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.
Otherwise, simply ignore the AJAX response.
AJAX requests may not complete in the order they were started. Instead of aborting, you can choose to ignore all AJAX responses except for the most recent one:
Create a counter
Increment the counter when you initiate AJAX request
Use the current value of counter to "stamp" the request
In the success callback compare the stamp with the counter to check if it was the most recent request
Rough outline of code:
var xhrCount = 0;
function sendXHR() {
// sequence number for the current invocation of function
var seqNumber = ++xhrCount;
$.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {
// this works because of the way closures work
if (seqNumber === xhrCount) {
console.log("Process the response");
} else {
console.log("Ignore the response");
}
});
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last
// one will trigger "Process the response" message
Demo on jsFiddle
We just had to work around this problem and tested three different approaches.
does cancel the request as suggested by #meouw
execute all request but only processes the result of the last submit
prevents new requests as long as another one is still pending
var Ajax1 = {
call: function() {
if (typeof this.xhr !== 'undefined')
this.xhr.abort();
this.xhr = $.ajax({
url: 'your/long/running/request/path',
type: 'GET',
success: function(data) {
//process response
}
});
}
};
var Ajax2 = {
counter: 0,
call: function() {
var self = this,
seq = ++this.counter;
$.ajax({
url: 'your/long/running/request/path',
type: 'GET',
success: function(data) {
if (seq === self.counter) {
//process response
}
}
});
}
};
var Ajax3 = {
active: false,
call: function() {
if (this.active === false) {
this.active = true;
var self = this;
$.ajax({
url: 'your/long/running/request/path',
type: 'GET',
success: function(data) {
//process response
},
complete: function() {
self.active = false;
}
});
}
}
};
$(function() {
$('#button').click(function(e) {
Ajax3.call();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button" value="click" />
In our case we decided to use approach #3 as it produces less load for the server. But I am not 100% sure if jQuery guarantees the call of the .complete()-method, this could produce a deadlock situation. In our tests we could not reproduce such a situation.
It is always best practice to do something like this.
var $request;
if ($request != null){
$request.abort();
$request = null;
}
$request = $.ajax({
type : "POST", //TODO: Must be changed to POST
url : "yourfile.php",
data : "data"
}).done(function(msg) {
alert(msg);
});
But it is much better if you check an if statement to check whether the ajax request is null or not.
Just call xhr.abort() whether it's jquery ajax object or native XMLHTTPRequest object.
example:
//jQuery ajax
$(document).ready(function(){
var xhr = $.get('/server');
setTimeout(function(){xhr.abort();}, 2000);
});
//native XMLHTTPRequest
var xhr = new XMLHttpRequest();
xhr.open('GET','/server',true);
xhr.send();
setTimeout(function(){xhr.abort();}, 2000);
You can abort any continuous ajax call by using this
<input id="searchbox" name="searchbox" type="text" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
var request = null;
$('#searchbox').keyup(function () {
var id = $(this).val();
request = $.ajax({
type: "POST", //TODO: Must be changed to POST
url: "index.php",
data: {'id':id},
success: function () {
},
beforeSend: function () {
if (request !== null) {
request.abort();
}
}
});
});
</script>
As many people on the thread have noted, just because the request is aborted on the client-side, the server will still process the request. This creates unnecessary load on the server because it's doing work that we've quit listening to on the front-end.
The problem I was trying to solve (that others may run in to as well) is that when the user entered information in an input field, I wanted to fire off a request for a Google Instant type of feel.
To avoid firing unnecessary requests and to maintain the snappiness of the front-end, I did the following:
var xhrQueue = [];
var xhrCount = 0;
$('#search_q').keyup(function(){
xhrQueue.push(xhrCount);
setTimeout(function(){
xhrCount = ++xhrCount;
if (xhrCount === xhrQueue.length) {
// Fire Your XHR //
}
}, 150);
});
This will essentially send one request every 150ms (a variable that you can customize for your own needs). If you're having trouble understanding what exactly is happening here, log xhrCount and xhrQueue to the console just before the if block.
I was doing a live search solution and needed to cancel pending requests that may have taken longer than the latest/most current request.
In my case I used something like this:
//On document ready
var ajax_inprocess = false;
$(document).ajaxStart(function() {
ajax_inprocess = true;
});
$(document).ajaxStop(function() {
ajax_inprocess = false;
});
//Snippet from live search function
if (ajax_inprocess == true)
{
request.abort();
}
//Call for new request
Just use ajax.abort() for example you could abort any pending ajax request before sending another one like this
//check for existing ajax request
if(ajax){
ajax.abort();
}
//then you make another ajax request
$.ajax(
//your code here
);
there is no reliable way to do it, and I would not even try it, once the request is on the go; the only way to react reasonably is to ignore the response.
in most cases, it may happen in situations like: a user clicks too often on a button triggering many consecutive XHR, here you have many options, either block the button till XHR is returned, or dont even trigger new XHR while another is running hinting the user to lean back - or discard any pending XHR response but the recent.
The following code shows initiating as well as aborting an Ajax request:
function libAjax(){
var req;
function start(){
req = $.ajax({
url: '1.php',
success: function(data){
console.log(data)
}
});
}
function stop(){
req.abort();
}
return {start:start,stop:stop}
}
var obj = libAjax();
$(".go").click(function(){
obj.start();
})
$(".stop").click(function(){
obj.stop();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="go" value="GO!" >
<input type="button" class="stop" value="STOP!" >
If xhr.abort(); causes page reload,
Then you can set onreadystatechange before abort to prevent:
// ↓ prevent page reload by abort()
xhr.onreadystatechange = null;
// ↓ may cause page reload
xhr.abort();
I had the problem of polling and once the page was closed the poll continued so in my cause a user would miss an update as a mysql value was being set for the next 50 seconds after page closing, even though I killed the ajax request, I figured away around, using $_SESSION to set a var won't update in the poll its self until its ended and a new one has started, so what I did was set a value in my database as 0 = offpage , while I'm polling I query that row and return false; when it's 0 as querying in polling will get you current values obviously...
I hope this helped
I have shared a demo that demonstrates how to cancel an AJAX request-- if data is not returned from the server within a predefined wait time.
HTML :
<div id="info"></div>
JS CODE:
var isDataReceived= false, waitTime= 1000;
$(function() {
// Ajax request sent.
var xhr= $.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
dataType: 'jsonp',
success: function(data) {
isDataReceived= true;
$('#info').text(data.talks[0].talk_title);
},
type: 'GET'
});
// Cancel ajax request if data is not loaded within 1sec.
setTimeout(function(){
if(!isDataReceived)
xhr.abort();
},waitTime);
});
This is my implementation based on many answers above:
var activeRequest = false; //global var
var filters = {...};
apply_filters(filters);
//function triggering the ajax request
function apply_filters(filters){
//prepare data and other functionalities
var data = {};
//limit the ajax calls
if (activeRequest === false){
activeRequest = true;
}else{
//abort if another ajax call is pending
$request.abort();
//just to be sure the ajax didn't complete before and activeRequest it's already false
activeRequest = true;
}
$request = $.ajax({
url : window.location.origin + '/your-url.php',
data: data,
type:'POST',
beforeSend: function(){
$('#ajax-loader-custom').show();
$('#blur-on-loading').addClass('blur');
},
success:function(data_filters){
data_filters = $.parseJSON(data_filters);
if( data_filters.posts ) {
$(document).find('#multiple-products ul.products li:last-child').after(data_filters.posts).fadeIn();
}
else{
return;
}
$('#ajax-loader-custom').fadeOut();
},
complete: function() {
activeRequest = false;
}
});
}

Google Recaptcha Ajax response strange checking order

I am making my registration page for my service. I need to check either Google's Recaptcha successfully verified or not. I decided to use an jquery.ajax.
I have created a function "checkCaptcha()" which sets isCAPT (if captcha valid or not) either true (FLD_VALID) or not (FLD_EMPTY):
function checkCaptcha() {
alert("1");
var captcha_response_text = grecaptcha.getResponse();
var request = $.ajax({
url: "ajax/registrationA.php",
type: "post",
data: { captcha: true, captcha_response: captcha_response_text }
});
request.done(function (response, textStatus, jqXHR) {
alert("2");
if(response) {
isCAPT = FLD_VALID;
}
else {
isCAPT = FLD_EMPTY;
}
});
}
I have to say that "registrationA.php" works fine. No problems there.
After this function, I am checking my submit button handling "onclick" event:
apply_button.onclick = function () {
checkCaptcha();
alert("3");
//alert("Капча " + isCAPT + " Логин " + isLOGIN + " Почта " + isMAIL + " Пароль " + isPASS + " Соответствие " + isPAS2);
return false;
};
You can see three "alert(...)" operators. The problem is that when I press submit button (apply_button) I get three alerts: 1, 3, 2. How can I fix this problem. I need to wait until "requiest.done" executes and only than go to "alert("3")". It is essential because now this function checks fields before checking captcha state which leads to an error because in this case isCAPT equals false.
Please help me with this problem. Maybe there is a better way to check if captcha verified or not (maybe there is a function like "grecaptcha.isVerified").
You need to check deferred.promise() method to work with asynchronous data. Check JQ documentation for that. In a few words it does exactly what you need. It allows to wait until the 2nd asynchronous request is finished and starts the 3d function.

How can I execute a query on success of jQuery

I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});

How to check if javascript function is ready/done (jQuery)

I am working on a learning planner which gets its data (languagekeys, tasks, activities, etc.) from a database. Because I need a JSON string, I encode it with json_encode to work with it in JavaScript.
I have a different function (for keys, tasks, activities, etc.) which gets this data and writes it into an array.
function get_tasks(start_date,end_date){
maxsubtasks=0;
maxtasks=0;
$.getJSON(json_data+"?t_startdate="+start_date+"&t_enddate="+end_date, function(data) {
tasks=new Array();
$.each(data.tasks, function(i,item){
tasks[i]= new Object();
tasks[i]["t_id"]=item.t_id;
tasks[i]["t_title"]=item.t_title;
tasks[i]["t_content"]=item.t_content;
. . .
if ( i > data.tasks.length) return false;
maxtasks = data.tasks.length;
if(item.t_parent > 0){
maxsubtasks++;
}
});
});
return true;
}
Everything is working just fine. I need some help, because I now have to call this function in $(document).ready(). I want to build my learning planner only once the function get_tasks() is complete (the array is filled with data). Otherwise, I will get errors.
How can this be solved?
Here is what I have in $(document).ready():
if(get_tasks(first_day,last_day) && get_tmp_data()){ // If this function is done
// This function should be fired -- just like a callback in jQuery
init_learnplanner();
}
You can add a callback to the function:
function get_tasks(start_date, end_date, callback) {
Then after populating the array in the function, call the callback function:
if (callback) callback();
Now you can use the callback parameter to initialise the learning planner:
get_tasks(first_day, last_day, function() {
init_learnplanner();
});
You should be able to specify a callback in $.getJSON, which gets executed as soon the request is completed.
EDIT:
You're already doing this, but why don't you just call the second code block from the end of the callback funciton in $.getJSON?
Other answers haven't worked for me because I have 5 functions which use my data with $.getJSON, and I need to have collected all information to even start init_learnplanner().
After several hours of searching, I've discovered the jQuery function ajaxComplete, which works like a charm for me. jQuery tracks all ajax calls that have been fired and triggers anything assigned .ajaxComplete() when one is complete.
What I'm doing is usually something like this:
simple, looks like beginner but it works :) :D
<script type="text/javascript">
var isBusy = true;
$(document).ready(function () {
// do your stuff here
isBusy = false;
});
function exampleajax() {
if(isBusy) return false;
isBusy=true;
$.ajax({
async: true,
type: 'POST',
url: "???.asp",
dataType: "jsonp",
data: qs,
error: function(xhr, ajaxOptions, thrownError){
//console.log(xhr.responseText + " AJAX - error() " + xhr.statusText + " - " + thrownError);
},
beforeSend: function(){
//console.log( "AJAX - beforeSend()" );
},
complete: function(){
//console.log( "AJAX - complete()" );
isBusy = false;
},
success: function(json){
//console.log("json");
}
});
}
</script>
hope this help you

Categories