I'm working on Cordova hybrid mobile app. I'm calling an API to load data into my variables and process it. Below is the problem.
First, I call the API using ajax. After ajax call, I check if jsonString is empty and if it is, I reload the page to run the ajax call again.
$.ajax({
url: GetConfigUrl // working URL,
type: 'POST',
data: {
token: '123456'
},
cache: false,
datatype: 'json',
contenttype: "application/json",
success: function (data, response, xhr) {
debugger
jsonString = data.Value;
},
error: function (data) {
// do nothing
)
});
if (jsonString == '') {
// Display popup to ask user the reload the page
}
return true;
I have a debugger in place in the success call function, but it does not hit and directly go to check if jsonString is empty, which is empty because it does not call the ajax to load data and proceed to display popup to ask user to reload the page.
After hitting the page reload, the debugger in the success call is being hit and able to retrieve the value. Thus the jsonString is not empty and able to proceed.
I check the Network tab in the console, it shows the below result:
It seems that the first call was made but always remain pending. The second call is the success one and return the correct value. So the jsonString checking is passed.
This issue happen all the time where the first ajax call is not success and in pending but all subsequent calls are successful.
So what could be wrong here? How do I ensure that the first ajax call will be made successfully and return the data all the time?
Ajax is executed asynchronous place your logic in the success function for it to get executed when the ajax call completes
$.ajax({
url: GetConfigUrl // working URL,
type: 'POST',
data: {
token: '123456'
},
cache: false,
datatype: 'json',
contenttype: "application/json",
success: function (data, response, xhr) {
debugger
jsonString = data.Value;
if (jsonString == '') {
// Display popup to ask user the reload the page
}
},
error: function (data) {
// do nothing
)
});
return true;
Related
I'm trying to call a web service to get some data. I need pass this URL in a GET method:
http://localhost/ecosat/ws/api.php?t=vw_motorista
But, when I look in Chrome Developer Tools, the link is:
http://localhost/ecosat/ws/api.php?t=vw_motorista&_=1397500899753
I'm not passing this parameter: &_=1397500899753
With this additional parameter, I received a 500 error. I can't change the web service to handle this.
What's going on? Is Chrome is changing my code?
This my Ajax
function get(pURL, pToken) {
var ret = null;
$.ajax({
type: "GET",
dataType: "json",
async: false,
timeout: globalTimeOut,
cache: false,
url: pURL,
headers: {"Token": pToken},
error: function(request, status, error) {
ret = null;
},
success: function(data) {
ret = data;
}
});
return ret;
}
You're probably using cache: false setting in your ajax query. It adds a _ parameter with a timestamp value, to make sure that your ajax call doesn't get cached by the browser.
Remove this setting, if you don't need it. But if you need make sure caching is disabled, you could try two things:
add your own parameter with a timestamp to your query, e.g. {ts: new Date.getTime()}, or
if possible, add headers to the web server response. See this question
I'm using jQuery to perform following AJAX request:
jQuery.ajax({
url: "url-to-script",
dataType: "html",
async: false,
success: function(data) {
console.log(data);
},
error:function(){
showMessage('Chyba', 'error');
}
});
Script that I'm calling is returning part of HTML. It is working properly.
But when I call this AJAX it will end with blank response in data. When I call it again it will return what it should and each next call is working. But the first one after page load is never working. I've no idea why.
I've also tried
if (data)
// do something
else
try again
But it just freeze my browser. So I don't know what is wrong.
Thanks for ideas!
I have the following code. The function is called multiple times depending on the user checking or unchecking checkboxes.
This works in all browsers except IE10/11. In IE, the ajax call is only made once for a particular ID. Subsequent calls are not actually sent to the server, but appear to be fetched from the cache.
In F12 developer tools, the call appears to be being made to the server, but Fiddler shows that it is not actually happening.
F12 also shows a 304 response to the call.
How do I ensure that the call is always made to the server?
function updateReportTypes(event) {
var value = event.currentTarget.value;
if (event.currentTarget.checked) {
$.ajax({
url: "/PropertySearch/Order/AddReportType?id=" + value,
dataType: 'html',
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
}
else {
$.ajax({
url: "/PropertySearch/Order/RemoveReportType?id=" + value,
dataType: 'html',
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
}
}
Simple set the:
cache: false
argument to $.ajax(). When you do that, jQuery will automatically add a unique paramter onto the URL which prevents any caching of the request.
Using that option would look like this:
$.ajax({
url: "/PropertySearch/Order/AddReportType?id=" + value,
dataType: 'html',
cache: false,
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
jQuery doc on this option: http://api.jquery.com/jquery.ajax/
I'm not familiar with this specific issue, but if all else fails, you should be able to add a dynamic, cache-busting value, such as a timestamp, to make your URL unique:
url: "/PropertySearch/Order/RemoveReportType?id=" + value + "&" + Date.now().toString()
I have a basic ajax call to parse a json file. I need to make sure I am not hitting the feed every time someone visits the page. How would I go about adding some sort of cache so the feed only get's requested say every say 2 hours?
$(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
May be you can use cookie store your time and check every time to know 2 hours time gap then you can call your function get the latest feed.
By default, is should get cached. You can set the option explicitly as shown below.
$(function () {
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
You can also use the below statement for all ajax calls on the page.
$.ajaxSetup({cache: true});
How to modify below code to use 'success' to call testMethod() in code-behind ?
I need to wait for return value from testMesthod() and process it.
$.ajax( {
url : 'myPage.aspx/testMethod',
type : "POST",
contentType : "application/json; charset=utf-8",
data : "{'name':'" + aNb + "'}",
dataType : "json"
}).done(function() {
alert("ok");
}).fail(function() {
alert("not ok");
});
Above code does not work because somehow latest JQuery version (1.10.1) gets overwritten by 1.3.2.
Thank you
You would need to pass the callback function to the function that wraps your $(ajax).
function getData(ajaxQuery, callBack){
var ajaxHREF = 'your url';
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
},
However, a much better way of doing this is the global success event. It is better because you have all of the properties of the call available to you to enable dynamic processing of the results. Create the global success event inline = $(document).ajaxSuccess this gets called for all jquery ajax success events so you need to differentiate which calls apply to your specific handler (to each global handler).
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var mimeType = settings.mimeType;
if (query.match(/ameaningfulvalueforthishandler/)){
if(mimeType.match(/application\/json/)){
var jsonData = $.parseJSON(xhr.responseText);
}
}
}
Thank for replies, but I still do not see how callbacl can help me.
I need to call webmethod in code-behind: testMethod()
Ajax call does it, url = "myPage.aspx/testMethod" will 'call' webmethod testMethod(),
but it's asynchronous and returns quickly into 'success' section of ajax call.
But, I need to Wait for testMethod() to finish processing, retrieve result returned by testMethod() and process it.
Asynchronous ajax will return us into 'success' without waiting for testMethod() to finish,
and we will not get any data in response.
So, how callback helps me to achieve it?
function getData(ajaxQuery, callBack){
var ajaxHREF = "myPage.aspx/testMethod";
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
});
Thank you
#Karen Slon - If I understand the question correctly, I think you need to conceptually separate the client side from the server side. The callback in .success/.done or global ajaxSuccess event enable your web page to initiate the request and keep on processing while the server side is processing your request 'myPage.aspx/testMethod'. When it completes successfully it returns to the success event. Now if testMethod does not return anything then you will find yourself in the success event event without a result. But you cannot get there unless web method testMethod has completed successfully and returned control. The .done event in your example only has alert("ok");. What makes you believe that the web method testMethod is not complete when the .done event occurs?
Look at these posts for better examples:
jQuery.ajax handling continue responses: "success:" vs ".done"?
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://api.jquery.com/category/deferred-object/