Here is the situation. I have an application in phonegap/jquerymobile. I want to change the page according to the json data.
When a user starts the app but the current version is not the latest version it needs to change content. This is a fragment of code from the start.html page.
<script type="text/javascript" charset="utf-8">
var versionValue = ServerSettings.versionCheck();
if(versionValue == true){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else{
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
</script>
The function ServerSettings.versionCheck() is below.
versionCheck : function() {
var localAppVersion = 0.8;
var response = false;
$.ajax({
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
response = true;
}
else{
response = false;
}
}
});
return response;
}
I have verified the response of the json call with a toast. It does get correct response.(version: 0.9) I am pretty sure i make the most dumbest mistake ever but i cannot seem to find it.
You are attempting to be synchronous, but the config parameter is evaluating to true because it's a string
async: "false"
Change it to async: false, but I'd recommend to switch to asynchronous to avoid blocking the UI.
Also your success callback doesn't return to the outer method, so you'll always get undefined.
versionCheck : function() {
var localAppVersion = 0.8;
var response = false;
$.ajax({
// WARNING: I don't recommend setting this to false in production code
// While the browser is waiting for the response the page/browser will not respond!!
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
response = localAppVersion == currentAppVersion;
}
});
return response;
}
To make it asynchronous (Recommended approach)
versionCheck : function(checkCompleteCallback) {
var localAppVersion = 0.8;
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
checkCompleteCallback(localAppVersion == currentAppVersion);
}
});
}
// Now the check accepts a callback function that executes when the request completes without blocking the UI
ServerSettings.versionCheck(function(versionValue) {
if(versionValue){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else {
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
});
It is due to you trying to access a value that has not been returned yet from the server as your are using asynchronus.
You could refactor you version check to take a callback argument like so.
<script type="text/javascript" charset="utf-8">
var localAppVersion = 0.8,
versionValue =false;
var versionValue = ServerSettings.versionCheck(function(jsonData){
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
versionValue = true;
}
else{
versionValue = false;
}
if(versionValue == true){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}else{
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
});
versionCheck : function(callback) {
var localAppVersion = 0.8;
var response = false;
$.ajax({
async: "false",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: callback
});
}
Version check is an asynchronous call. So, it will not return true or false. Your versionValue will not be true or false. It is better use promises for asynchronous calls.
Change your versionCheck function like this
versionCheck : function() {
var localAppVersion = 0.8;
var response = false;
$.ajax({
async: "false",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
return true;
}
else{
return false;
}
}
}).done(function(){
if(versionValue == true){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else{
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
});
}
jQuery.promise is available in version > 1.6
Ajax works asynchronously, so when you do the check the response actually is not arrived yet. Put the logic that depends from that value inside the ajax callback.
versionCheck : function() {
var localAppVersion = 0.8;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else {
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
}
});
}
Related
I have a strange problem with the below AJAX jQuery method to call a webmethod in an asmx service. It's not firing when I try to call it, but the moment I uncomment any of the alert in code to debug, it works all of sudden.
It confuses me, what would be the problem? Am I missing something here..
Code:
var endXsession = function() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msge) {
//alert(msge.d);
fwdURL = msge.d;
},
error: function(response) {
//alert(response.responseText);
fwdURL = response.responseText;
}
});
//alert(fwdURL);
return fwdURL;
};
response.responseText is undefined ... it's response.statusText ..
function endXsession() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msge) {
// alert(msge.d);
fwdURL = msge.d;
}
,
error: function (response) {
// alert(response.statusText);
fwdURL = response.statusText;
}
});
// alert(fwdURL);
return fwdURL;
}
console.log(endXsession());
i'm trying to make infinite scrolling so when scrolling i make an ajax request to the server to get data but when scrolling a multiple ajax request is made and return the same data so how can i cancel ajax request before sending if there one already exist i tried like this
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
all my code
var lock_load = '1';
var activeAjaxConnections = 1;
var PageNumber = 2;
$(window).scroll(function () {
if ((Math.ceil($(window).scrollTop() - $(window).height()) * -1) <= getHeight() + 550) {
if (lock_load === '1') {
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
alert(errorThrown);
n }
});
}
}
});
but it give an error xhr is undefined pleas any help and many thanks in advance.
Try flags
Before making ajax call set flag to true and after ajax call is made set flag to false, finally on completion of ajax request again set flag to ture
var ready = true;
$(window).scroll(function(){
if(ready == true){
ready = false;
$.ajax({
url: "/pagination",
cache: false,
success: function (response){
//response
}
}).always(function () {
ready = true; //Reset the flag here
});
}
});
use the below code, use a simple flag variable that will be set to false by the defualt, that is to say that ajax call is not occuring once if condition is met then it will set to true to say that ajax call has started, once the success: or error: call back fires the variable will be set to false so that another ajax call can be made.
startedAjax = false;
if (lock_load === '1') {
startedAjax = true;
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
startedAjax = false //set is false
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
startedAjax = false;
alert(errorThrown);
}
});
}
}
});
this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
Now if I call var count = getMessageCount();
it gives me undefinted :(
while inside the method count is coming correct, i.e. service is working fine.
I agree with the first line by ahren that
'That's because the $.ajax() call is asynchronous.'
you could try adding a setting - async:false
which is true by default. This makes the call synchronous.
you can edit your code as :
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
That's because the $.ajax() call is asynchronous.
If you edit your code to something like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if(typeof callback === "function") callback(count);
} //success
});
}
Then when you call it:
getMessageCount(function(count){
console.log(count);
});
use a callback:
call function like:
getMessageCount(function(result) {
//result is what you put in the callback. Count in your case
});
and the other like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if (callback) {
callback(count);
}
} //success
});
}
Why you don't just pass it to a function?
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
countMessages(count);
} //success
});
}
function countMessages(counted) {var counted = counted; console.log(counted);}
function ajax_call(url,data){
return $.ajax({ type: "POST",
url: url,
data: data,
async:false,
success: function(status){
}
}).responseText;
}
Now you will get the response text from server side via ajax call
I am calling live('click') function in which i call ajax method and do some server side functionality.
But before ajax call i need to check for valid data.
Am bit confused how to call it
// Depend on this condition i have to start process my ajax function.
function validData()
{
if ($('.edt').val() == "")
{
return false;
}
var maxtxtvalue = $('edt3').val();
var mintxtvalue = $('edt4').val();
// alert(maxtxtvalue > mintxtvalue);
if(parseInt(maxtxtvalue) > parseInt(mintxtvalue))
{
return true;
}
else
{
$('input:text[id$="txtmaxctc"]').val('');
$('input:text[id$="txtminctc"]').val('');
alert("Max ctc must be greater then Min ctc.");
return false;
}
}
$("img[class^='sav_']").live('click', function (event) {
if( return false )
{
}
else{
//start process
$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/upajx",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
} });
}
});
// Depend on this condition i have to start process my ajax function.
can't you do like this..
function validData()
{
if ($('.edt').val() == "")
{
return false;
}
var maxtxtvalue = $('edt3').val();
var mintxtvalue = $('edt4').val();
// alert(maxtxtvalue > mintxtvalue);
if(parseInt(maxtxtvalue) > parseInt(mintxtvalue))
{
return true;
}
else
{
$('input:text[id$="txtmaxctc"]').val('');
$('input:text[id$="txtminctc"]').val('');
alert("Max ctc must be greater then Min ctc.");
return false;
}
}
$("img[class^='sav_']").live('click', function (event) {
if(validData() )
{
}
else{
//start process
$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/upajx",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
} });
}
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
function Run(someJsonObject) {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
}
var result = Run({dummy:'dummy'});
If I'm not mistaken, the above function will not return true or false, but rather it will be undefined. I want to return the result of the AJAX call, I'd prefer to make it synchronous (I realize I'm using AJAX). How would I accomplish this?
You are backwards, let your ajax run first.
$(function () {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
DoStuffWithResult(data.d);
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
});
function DoStuffWithResult(result){
//time to rock, i have my result
}
If you add the async option to your jquery call, it stops being asynchronous.
That being said, this is usually a bad idea and can probably be handled a better way. Usually, this is done by doing your ajax call first and working with your data in your success function.
If you are really adamant about doing it this way, though, this is what you want:
function Run(someJsonObject) {
var result;
$.ajax({
async: false,
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
result = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
result = false;
}
});
return result;
}
var result = Run({dummy:'dummy'});
If you want to make an ajax request in jquery synchronous and have it be the return value of Run:
function Run(someJsonObject) {
var returnValue;
$.ajax({
type: "post",
async: false,
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
returnValue = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
returnValue = false;
}
});
return returnValue;
}
I added async: false to the ajax options and used a local variable (accessible to the success and error handlers) as the return value.
You can't just return $.ajax(/* snip */) because that returns a promise object.
You can simplify
$.post('/MyWebService', JSON.stringify(someJsonObject), function(r) {
if(r.success) {
// do something (1)
} else {
// do else something (2)
}
},'json').error(function() {
alert('comunication error');
});
If you get any response like this
{ "success": true, data: "my_data" }
execute something (1)
else (2)
If not a valid json or timeout trigger .error()