Chrome only : ajax freezing my javascript execution - javascript

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

Related

Ajax inside Ajax somehow strange behaviour

I have a Ajax-Call inside a Ajax-Call, everything "seems" to work fine. In console I can see, both calls are executed and get a return.
But somehow, i can't use the returned result from the second call(?)
$.ajax({
type: "POST",
url: "register/checkEmail/"+email,
success: function(result){
if(result == "TRUE") {
$('#regMsg').html('Ein User mit dieser Email ist bereits registriert!');
$('#regMsg').slideDown();
// NO ERROR - REGISTER USER
} else {
$('#regMsg').slideUp();
var inputs = $('#regForm :input').serializeArray();
alert('ok');
$.ajax({
method: "POST",
url: "register/save",
data: inputs,
dataType: 'json',
success: function(result){
alert('ddok');
}
});
}
}
});
the first alert() is beeing displayed, the secont is not, although the second call is executed correctly(?) why is that?
Simple - the second call's response did not return back to the ajax i.e error/fail.
Add the error handling part after success to find the response.
After success add
,error: function(result){
alert('error');
console.log(result);
}
If this is not the reason, then dataType: 'json', should be the culprit as your response wouldn't be in json format !!

unable to show record using webservice

this code is working fine but not showing records. in alert if i am getting record from file its working fine.
$j().ready(function(){
var result =$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
Welcome to the wonderful world of asynchronous ...
First of all, jQuery get doesn't return the data, that needs to be handled by the callback (which is working as from your post)
var result = null;
$j(document).ready(function(){
$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
result = data;
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
This might not work as well since jQuery ajax is asynchronous and the alert may pop up while the GET is still reading data and not yet ready !!!!
Check Jquery ajax doc:
$.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8'
}).done(function(data) {
console.log(data);
});
The javascript is not waiting AJAX to finish, it moves on. That is why its called asynchronous . If you need synchronous call, use async: false.

javascript variable equal to value from function [duplicate]

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");
}

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 come this asyncronous call is not stopping on return false [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jquery ajax call taking too long or something
for some reason this ajax call
$('#new_user').submit(function(e){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
}
}
});
});
is still submitting the form even after prints out my error and my return false....why is that
$.ajax is a function call which defines an AJAX callback then and the .submit function ends. Separately (asynchronously) the AJAX call is made and your success function then returns false to basically nothing since .submit has already finished.
What you really want to do is halt the form submission process, waiting for the AJAX call to finish, then decide if it should continue. This can be achieved by completely stopping the form submission the first time, then manually resubmitting it once you've got the AJAX callback. Of course the trick is how do you know it's valid? You could throw a value on the submit element.
Example:
$('#new_user').submit(function(e){
var submitElem = $(this);
// Check for previous success
if (submitElem.data('valid') !== true) {
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false) {
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
} else {
// If successful, record validity and submit (allowing to continue)
submitElem
.data('valid', true)
.submit();
}
}
});
return false;
} else {
// Fall through
return true;
}
});

Categories

Resources