JQuery Ajax call, return value problem - javascript

function getMore(from){
var initData = "&start-index=";
initData += from;
$.ajax({
type:"POST",
url: '', //removed the URL
data: initData,
dataType: 'json',
success: function(result) {
return result;
},
error: function(errorThrown) {
}
});
return result;
}
Its a google base query; I have another function that makes the initial server call and gets the first 250 items. I then have a running counter and as long as the results = 250 it calls the server again, but starting at "start-index=" of the current amount of items pulled off. This part all works correctly and with firebug I can also see that the server response is proper JSON.
The trouble I'm having is trying to return the JSON from this function to the function that called it. I do not want to call the original function again because it will clear the arrays of data already pulled from the server. Each time it returns to the parent function it's null.
Does anyone know how i can go about returning the data using "return"?

function FuncionCallGetMore(){
//...
getMore('x-value', FuncionGetReturn);
//...
}
function FuncionGetReturn(error, value){
if (!error) {
// work value
}
}
function getMore(from, fn){
var initData = "&start-index=" + from;
$.ajax({
type:"POST",
url: '', //removed the URL
data: initData,
dataType: 'json',
success: function(result) {
fn(false, result);
},
error: function(errorThrown) {
fn(true);
}
});
return;
}

The only way that you can do what you're describing is to make the AJAX call synchronous, which you don't want to do since it will lock the UI thread while the request is being made, and the browser may will to freeze. No one likes freezing.
What you want to do is use callbacks. Post the code of the other functions involved so I can get a better idea of what is going on. But basically, what you want to do is to create an asynchronous loop.
function listBuilder() {
var onError = function(response) {
// ...
};
var onSuccess = function(response) {
// Handle the items returned here
// There are more items to be had, get them and repeat
if ( response.length == 250 ) {
getMore(onSuccess, onError, 250);
}
};
getInitialSet(onSuccess, onError);
}
function getMore(onSuccess, onError, from) {
$.ajax({
type:"POST",
url: '', //removed the URL
data: "&start-index=" + from,
dataType: 'json',
success: onSuccess,
error: onError
});
}

Related

jQuery multiple ajax calls inside for loop logging same responses

My code is something like this:
for (var i = 0; i < stf_file_names.length; i++) {
var temp_file_name = stf_file_names[i];
$.ajax({
type: "POST",
url: "php_scripts/some_script.php",
data: {
stf_file_name: temp_file_name
},
timeout: 600000,
success: function (response) {
console.log("SUCCESS : ", response);
//pausecomp(2000);
}
});
}
Here, some_script.php updates a database in the backend and echo's the primary key of the updated row, which is a number. But when I'm logging using the success function, I can see that it is logging only the primary key echoed by the last ajax call multiple times.
But if I use some kind of sleep function, which is pausecomp() in this case, it prints different the primary keys echoed.
I have looked at multiple stackoverflow questions regarding this and have not been to solve it.
async: false will do the job
$.ajax({
type: "POST",
async: false,
url: "php_scripts/some_script.php",
data:
However, this is not recommended, Better to make a loop by calling a function recursively from success.
Here is the example.
i=0;
function loop_stf_file_names(i){
var temp_file_name = stf_file_names[i];
$.ajax({
type: "POST",
url: "php_scripts/some_script.php",
async: false,
data: {
stf_file_name: temp_file_name
},
timeout: 600000,
success: function (response) {
console.log("SUCCESS : ", response);
if( i < stf_file_names.length ){
loop_stf_file_names( ++i );
}
}
});
}
$.ajax() is a async function.
By looping over ajax you are most probably sending the same data in all requests, due to which you are receiving same key for all requests.
Just sure , you send the next request when you have received the response from first request.

Jquery Asynchronous call return undefined value

I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.
funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
url: path,
type: method,
data: params,
async: false,
beforeSend: function() {
$('.black_overlay').show();
},
success: function(data){
console.log(data);
resp = callbackFunction(data, obj);
if(alerter==0){
if(obj==null) {
resp=data;
} else {
obj.innerHTML=data;
}
} else {
alert(data);
}
},
error : function(error) {
console.log(error);
},
complete: function() {
removeOverlay();
},
dataType: "html"
});
return resp;
}
The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.
In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.
Is there any way to solve both problems? I would get beforeSend function and resp value both.
Thanks
Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:
var resp = '';
$('.black_overlay').show();
$.ajax({
...
Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.
Take the resp variable out from the function
Create one extra function respHasChanged()
when you get the data successfully, use the code
resp = data;respHasChanged();
You can restructure on this way, (why no use it in async way?)
function ajaxCall(path, method, params) {
return $.ajax({
url: path,
type: method,
data: params,
beforeSend: function() {
$('.black_overlay').show();
},
dataType: "html"
});
}
Call in your javascript file
ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
.done(function(data) {
console.log(data);
// DO WHAT YOU WANT TO DO
if (alerter == 0 && obj !== null) {
obj.innerHTML = data;
} else {
alert(data);
}
}).fail(function(error) {
console.log(error);
}).always(function() {
removeOverlay();
});

Ajax - All request are Done/Completed

I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.

Jquery Ajax beforeSend and success,error & complete

I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax.
The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).
While debugging it shows that the beforeSend function of the second ajax call is called first and the complete function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.
In short it's mixed up. Is there any way this can be sorted out?
The function code is as follows
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
$(placeholder).removeClass('loading');
},
dataType: 'html'
});
}
And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.
<script type="text/javascript">//<!--
$(document).ready(function() {
$('#restart').val(-1)
$('#ajaxSubmit').click();
});
//--></script>
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: #get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Promote callback onSuccess return value to the Caller Function return value

I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.
A super-simplified version of the generic function without all my logic would be:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
return true;
else
return false;
},
error:
function(errorThrown) {
return false;
}
});
}
And the function calling it would be something like:
function Next() {
var result = CallServer("/Signum/TrySave");
if (result == true) {
document.forms[0].submit();
}
}
The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.
Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?
Thanks
Just in case you want to go the asynchronous way (which is a better solution because it will not freeze your browser while doing the request), here is the code:
function CallServer(urlController, callback) {
$.ajax({
type: "POST",
url: urlController,
async: true,
data: $("form").serialize(),
success:
function(result) {
var ret = ( someLogic );
callback(ret);
},
error:
function(errorThrown) {
return false;
}
});
}
function Next() {
CallServer("/Signum/TrySave", function(result) {
if (result == true) {
document.forms[0].submit();
}
});
}
I usually put any code to be executed on success inside the callback function itself. I don't think CallServer() actually receives the return values from the callbacks themselves.
Try something like:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
document.forms[0].submit();
else
// do something else
},
error:
function(errorThrown) {
// handle error
}
});
}
Edit: I'm not too familiar with jQuery, so I might be completely wrong (I'm basing this on the behavior of other frameworks, like YUI, and AJAX calls made without any framework). If so, just downvote this answer and leave a comment, and I will delete this answer.
Just found how to do it :) Declaring a variable and updating it accordingly from the callback function. Afterwards I can return that variable. I place the code for future readers:
function CallServer(urlController) {
var returnValue = false;
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic){
returnValue = true;
return;
}
},
error:
function(errorThrown) {
alert("Error occured: " + errorThrown);
}
});
return returnValue;
}

Categories

Resources