javascript variable equal to value from function [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?
So I have a javascript function where I'm doing an AJAX call to see if the user is online or offline. It looks something like this.
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
return html;
}
});
}
I would like to assign the value from this function as a variable that I can then use.
Something like this.
var test = onlineStatus();
if (test == "true")
alert("online");
else
alert("offline");
Is this possible? I must be doing something wrong, but can't figure out how to achieve this result. Thanks
// Edit:
Thanks for your help everyone, sorry, didn't realize it may have been a duplicate question. I wasn't sure what to search for initially, so I didn't see anything related.

$.ajax is asynchronous so you can't return anything from onlineStatus, you need to pass it a callback function that can be called when the ajax call completes.
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
});
}
onlineStatus(function(test) {
if (test == "true")
alert("online");
else
alert("offline");
});

Since calls happen asynchronously, you'll have to pass a callback function into onlineStatus. Something like:
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
callback(html);
}
});
}
And then call it with:
onlineStatus(function (html)
{
// Do stuff with the status
});

You can simple use a deferred object.
function onlineStatus(){
var request = $.ajax({
url: "assets/ajax/online-offline.php",
cache: false
});
return request;
}
var test = onlineStatus();
test.done(function(html) {
if (html)
alert("online");
else
alert("offline");
});
$.ajax returns a jqXHR, so you can use .done:
jqXHR.done(function(data, textStatus, jqXHR) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated

AJAX is asynchronous, that's what the A stands for. You need pass a callback.
For example:
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
});
}
onlineStatus(function(data) {
if (data == "true") {
alert "online";
}
else {
alert "offline";
}
}

The $.ajax method is asynchronous so you need to handle its return values in the callback.
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
if (html == "true")
alert("online");
else
alert("offline");
}
});
}

you can do like this.......but it is not a good method because synchronous request by ajax makes your code slow.......
function onlineStatus(){
var data;
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
async:false,
success: function(html){
data = html;
}
});
return data;
}
or
if you only want to dispaly the alert box then...
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
if (html== "true")
alert("online");
else
alert("offline");
}
});
return data;
}

jQuery ajax call is an asynchronous call. You will have to wait to get the results before you can use them for showing the alert.
var isOnline = false;
checkOnlineStatus();
function checkOnlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
}
});
}
function callback(html){
isOnline = (html == "online");
showAlert();
}
function showAlert(){
if (isOnline == "true")
alert("online");
else
alert("offline");
}

Related

Chrome only : ajax freezing my javascript execution

Ajax means asynchronous, but it seems like its stopping my javascript execution or at least pausing it and resuming on response.
HTML value
<input value="foo" data-loading-text="bar" class="foo">
Extending jquery -->
$.fn.bootstrapButton= function(type){
$el = $(this);
loadingText = $el.attr("data-loading-text");
currentValue = $el.val();
if(type === "loading")
$el.attr("data-loading-text",currentValue)
.val(loadingText)
.prop("disabled", true)
else if( type === "reset")
$el.val(loadingText)
.prop("disabled", false)
.attr("data-loading-text", currentValue)
}
Function call -->
save= function (name){
$save = $(".ok")
$save.bootstrapButton("loading")
$.ajax({
type: 'POST'
url: '/server'
cache: false
dataType: 'json'
data:"ss"
success: function(response){
alert("success")
}).always(function(){
$save.bootstrapButton("reset")
})
}
I'm extending bootstrap's button coz of jquery UI's button problem. But -- when this is executing, I never see the loading text until ajax request is completed!! da faq!. Asynchronous isn't true asynchronous?
BTW, the code works without any glitch ( I can see the loading text ) with this small modification.
save= function (name){
$save = $(".ok")
$save.bootstrapButton("loading")
setTimeout(funtion(){
$.ajax({
type: 'POST'
url: '/server'
cache: false
dataType: 'json'
data:"ss"
success: function(response){
alert("success")
}).always(function(){
$save.bootstrapButton("reset")
})
},100)
}
i.e, with a 100 millisec delay, the loading text appears!, what gives?
The construction:
$.ajax({
....
}).always(function(){
$save.bootstrapButton("reset")
})
says: "Execute this Ajax command, and when it is done always run this anonymous function.
So you've explicitly said, "wait until the Ajax call is done", and it's working.
Adding the below as an option in my ajax query solved the issue.
async: true

Return statement executes before ajax response

I am making an ajax call on submit button click event to check field validations server side.
When I get a validation fail, ajax response gives the proper error message, returns false, and stops the form to submit to the action url. But when I get a response of 'success', the form is still not submitting to the action url script.
Is this the case when return statement executes before ajax response?
And also why is the form not getting submitted?
Here is the code:
<input type="submit" onclick="return validate();" name="submit" value="Proceed" />
<script type="text/javascript">
var flag=false;
function validate(){
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
success: function (result) {
if(result.toString() == "success" ){
flag=true;
}
else{
$('#error').css('display', 'block');
$('#error').css('color','red');
$('#error').text(result.toString());
flag=false;
}
}
});
return flag;
}
</script>
one Way is
use async : false
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
async : false,
success: function (result) {
And also why are you returning the value outside the ajax function , return the value inside ajax success if you are not using async : false
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
success: function (result) {
if(result.toString() == "success" ){
flag=true;
}
else{
$('#error').css('display', 'block');
$('#error').css('color','red');
$('#error').text(result.toString());
flag=false;
}
}
return flag;
});
Ajax is asynchronous, so you should just pass a function to the function as an argument, and then execute it on success of the ajax call.
function my_callback() {
alert('done');
}
function validate(cb) {
$.ajax({
/* ... */
success: function() {
cb();
}
});
}
The function you pass to validate will be executed upon the success function call.

Check if some ajax on the page is in processing?

I have this code
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt2='+txt2,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Suppose user clicked on #postinput and it takes 30 seconds to process.If in the meantime user clicks on #postinput2 . I want to give him an alert "Still Processing Your Previous request" . Is there a way i can check if some ajax is still in processing?
Suppose I have lot of ajax running on the page. Is there a method to know if even a single one is in processing?
You can set a variable to true or false depending on when an AJAX call starts, example:
var ajaxInProgress = false;
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
ajaxInProgress = true;
$.ajax({
..
..
success: function(html) {
ajaxInProgress = false;
Now check it if you need to before a call:
if (ajaxInProgress)
alert("AJAX in progress!");
Or, use global AJAX events to set the variable
$( document ).ajaxStart(function() {
ajaxInProgress = true;
});
$( document ).ajaxStop(function() {
ajaxInProgress = false;
});

Trigger success handler is finished executing, with nested ajax requests

I have many nested ajax requests like below. I have a lot of things going on in the success function below, I need something like success that will trigger when success is complete. complete(jqXHR, textStatus) just seems to fire with success and I don't think .ajaxComplete() works.
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests
},
});
SOLUTION:
A $.ajax() replacement plugin called $.fajax() (finished + ajax) has been created. Please check it out and let me know what you think. https://github.com/reggi/fajax (It's pretty well documented).
You could create a wrapper function for jQuery.ajax to make this a little cleaner:
var started = 0, done = 0;
var globalHandler = function(){
//do stuff when all success handlers are done
}
function handleAjax(args){
var _success = args.success || function(){};
args.success = function(jqXHR, textStatus){
_success(jqXHR, textStatus);
done++;
if(done >= started)
globalHandler();
}
var ajax = $.ajax(args);
started++;
return ajax;
}
usage
handleAjax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests like this:
handleAjax({...});
}
});
This creates a closure so don't do any crazy memory-intensive stuff in there and you should be fine.
I'm not quite totally sure of what you're asking, so forgive me if I'm off-kilter, but I think you might want something like:
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
},
}).done(function(msg){
alert("Every Ajax Call is Complete!");
});
You may want .queue() or .Defered
$("#el").queue("queue_name",function(){
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
$("#el").dequeue("queue_name"); // tell queue success is complete
},
});
}).queue("queue_name",function(){
//do something you want when success is complete
})
$("#el").dequeue("queue_name"); // start to execute
or $.Deferred()
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
var start = function(){
var dtd = $.Deferred();
//more nested ajax requests---------------
$.post("xxx",function(){
dtd.resolve(); // when success is complete
});
//----------------------------------------
return dtd.promise();
}
start.apply(this).pipe(function(){
//do something you want when success is complete
});
},
});

How to call second jQuery.ajax instance on success of first and update page

I have some jQuery that is triggered on click of a link with the class 'changetag'. I'm using $.ajax() to update the database via changetag.php.
I then change the visual appearance of the link by toggling the class between on/off. The code is as follows:
$(function() {
$(".changetag").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'switch_tag=' + I;
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){}
});
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
});
});
Works perfectly. But now I want to add in a second PHP call which will pull data and update another area of the page if the above was successful.
What I'm trying to add is:
$.ajax({
url: "_js/loaddata.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
But just adding it into success: function(){} doesn't seem to be working. To clarify, here is the complete code I'm testing:
$(function() {
$.ajaxSetup ({cache: false});
$(".changetag").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'switch_tag=' + I;
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$.ajax({
url: "_js/loaddata.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
});
});
The PHP scripts are both called successfully and the toggle class works, but the data pulled is not written to #listresults for some reason.
Ajax calls are (by default) asynchronous. That means that this code:
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
could be executed before the ajax call preceding it is finished. This is a common problem for programmers who are new to ajax and asynchronous code execution. Anything you want to be executed after the ajax call is done must be put into a callback, such as your success handler:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
Likewise, you could put the second ajax call in there as well:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
$.ajax({
url: "_js/loaddeals_v2.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
With jQuery 1.5's Deferred Object, you can make this slicker.
function firstAjax() {
return $.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
}
// you can simplify this second call and just use $.get()
function secondAjax() {
return $.get("_js/loaddata.php", function(results){
$('#listresults').html(results);
});
}
// do the actual ajax calls
firstAjax().success(secondAjax);
This is nice because it lets you un-nest callbacks - you can write code that executes asynchronously, but is written like synchronously-executed code.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
https://api.jquery.com/jQuery.ajax/#jqXHR

Categories

Resources