When I pass function() { location.reload(); } as a callback - it doesn't get invoked.
$('#swapLanguageLink').click(function() {
$.post('#Url.Action("SwapLanguage", "Language")', function() { location.reload(); });
//location.reload();
});
If I un-comment //location.reload(); (instead of passing callback) - it works nice, but I am not sure if it is async or not.
It can happen that my document will be reloaded before async operation is finished, right? So why my callback doesn't work?
Edit:
$.post('#Url.Action("SwapLanguage", "Language")', null, function () {
location.reload();
}).done(function () {
location.reload();
}).error(function () {
alert('error');
});
I've tried the code above. error get invoked. But "SwapLanguage" invokes. Something really strange to me!
Something like this:
jQuery.ajax({
type: "POST",
async: true,
url: '#Url.Action("SwapLanguage", "Language")',
success: function (data) {
location.reload();
},
error: function (err)
{
alert("error");
}
});
OR
$.post('#Url.Action("SwapLanguage", "Language")', null)
.done(function(data) {
location.reload();
});
Related
My Example works, but I want to now if it is a good way to send empty request like my example below.
$(document).ready(function () {
$("#home").click(function (e) {
// Prevent default form action
e.preventDefault();
// AJAX Request
$.ajax(
{
url: "/command/home",
type: "GET",
success: function (response) {
alert(response);
},
error: function (error) {
alert("Error!" + error);
}
});
});
});
Thank You!
In below code after ajax is completed or successed $(".cdmodels").append(result); does not executed but two next lines are executed. i have checked different way but it's not solved. please help me.
$('.load-more').on('click', function (e) {
e.preventDefault();
var count = $(this).attr('data-value');
var btn = $(this).button('loading');
$.ajax({
url: "#Url.Action(MVC.Library.Index())",
data: { count: count },
dataType: 'json',
async: true,
method: 'POST',
complete: function (result) {
$(".cdmodels").append(result);
btn.button('reset');
btn.attr("data-value", parseInt(count) + 1);
}
});
});
UPDATE:
browser debug:
Usually when you are working with AJAX calls and if you are struck you should debug as shown below
Log the response. console.log(response)
Check for the type of response. console.log(Object.prototype.toString.call(response)
$('.load-more').on('click', function (e) {
e.preventDefault();
var count = $(this).attr('data-value');
var btn = $(this).button('loading');
$.ajax({
url: "#Url.Action(MVC.Library.Index())",
data: { count: count },
dataType: 'json',
async: true,
method: 'POST',
complete: function (result) {
// In your case it should be result.responseText
$(".cdmodels").append(result.responseText);
btn.button('reset');
btn.attr("data-value", parseInt(count) + 1);
}
});
});
Have you checked it using a try/catch block?
...
complete: function (result) {
try{
$(".cdmodels").append(result);
btn.button('reset');
btn.attr("data-value", parseInt(count) + 1);
}catch(e) {
console.log("Something went wrong! Watch for 'e' and 'result'");
debugger;
}
}
...
start with devtools open.
The complete callback receives a object with several properties. You cannot directly use that to update your DOM. If you want you can use the responseText property.
This should work.
$(".cdmodels").append(result.responseText);
Or even better, use the done() callback
$.ajax({
url: "#Url.Action("Index")",
data: { count: 2 },
method: 'POST'
}).done(function (res) {
console.log('done');
$(".cdmodels").append(res);
});
The jqXHR.success(), error(), and complete() callbacks are removed as of jQuery 3.0. You should use jqXHR.done(), fail(), and always() instead.
In the following code, I want the alerts to come in order (1st call followed by the second), but it keeps coming the other way around. This is causing some variables to become undefined. What is the order of execution when having multiple ajax queries in the same code? How can I change the order of the alerts?
$(document).ready(function () {
function get_det() {
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
}
});
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function (result) {
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
get_det();
alert("2nd call");
//other code
}
}
});
Ajax is by default Asynchronous meaning there will be no wait for response.
That is why your 2nd call is calling before ajax request.
You can make ajax Syncronuous by setting async: false. Not recommended as it could cause browser hanging.
For Asynchronous process you can use callback function which only call when your request is completed.(Recommended)
In javascript you can do like this(For your code):
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
call like this:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
The difference in behavior is due to async nature of ajax calls. In your case, you want to perform some code once the call has executed, hence, you need to use callback functions.
Update your code to following
function get_det(callback) {
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
if(callback) {
callback();
}
}
});
}
function calculateAndDisplayRoute() {
//other code
get_det(function() {
/* this is the place where you need to put code
* that needs to be executed after the ajax has been executed */
alert("2nd call");
});
}
I suggest chaining the promises that $.ajax returns.
$(document).ready(function () {
function get_det() {
return $.ajax({
url: "aa.php",
type: "POST"
}).then(function(result) {
// Do some stuff - you can even modify the result!
// Return the result to the next "then".
return result;
})
}
// Named after the php script you're hitting.
function dd() {
// Return the promise from Ajax so we can chain!
return $.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php"
});
}
function initializeMap() {
// Do stuff before call
return get_det().then(function(getDetResult) {
// Do stuff after AJAX returns..
return {
getDetResult: getDetResult,
mapInitialized: true
};
});
}
// use it!
dd().then(function(result) {
alert('1st call');
// Pass result from dd to initializeMap.
return initializeMap(result);
}).then(function(initMapResult) {
alert('2nd call', initMapResult.mapInitialized);
});
});
I can't figure out why this isn't working, i've looked at many questions here at stackoverflow but can't find anything wrong with my code.
I have a #loading div that i want to remove when the ajax call is complete. This is my code and ajaxComplete is never called.
What am i doing wrong?
$(document).ajaxStart(function () {
console.log("ajax start");
$("#loading").show();
});
$(document).ajaxComplete(function () {
console.log("ajax complete");
$("#loading").remove();
});
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '#Url.Content("~/Service/listAllDevices")' + '?limit=' + 300 + '&offset=' + 10,
dataType: 'json',
async: 'false',
global: true,
success: function (listAllDevicesResponse) {
console.log("ajax done");
console.log(listAllDevicesResponse);
}
});
});
There is no ajaxComplete event handler for the $.ajax object, instead use done or always. There is also the complete event handler but it was deprecated as of jQuery 1.8.
$(document).ajaxStart(function () {
console.log("ajax start");
$("#loading").show();
});
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '#Url.Content("~/Service/listAllDevices")' + '?limit=' + 300 + '&offset=' + 10,
dataType: 'json',
async: 'false',
global: true,
success: function (listAllDevicesResponse) {
console.log("ajax done");
console.log(listAllDevicesResponse);
},
always: function() {
console.log("ajax complete");
$("#loading").remove();
}
});
});
You can read more about the jQuery $.ajax here.
I am not quite sure why your complete function is not called, however I would recommend using stop. ajaxComplete is called everytime an INDIVIDUAL ajax request finished. ajaxStop is called when ALL requests have finished. Like so:
$(document).ajaxStart(function () {
console.log("ajax start");
$("#loading").show();
});
$(document).ajaxStop(function () {
console.log("ajax complete");
$("#loading").hide();
});
References:
https://api.jquery.com/ajaxStart/
https://api.jquery.com/ajaxStop/
I have this jquery autocomplete code.Everything works fine data is loaded etc.Success is working.But when i have error...error handling is not working in below code.
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
if (value && value.length > 0) {
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
type: "GET",
url: "http://domain.com/food.php",
dataType: "jsonp",
crossDomain: true,
data: $(this).serialize(),
success: function (data) {
alert("success");
},
error: function () {
alert("an error occurred!");
},
beforeSend: function () {
// This callback function will trigger before data is sent
},
complete: function () {
setTimeout(function () {}, 1);
}
})
.then(function (response) {
$.each(response, function (i, val) {
//do something with data
});
}
});
As the jQuery doc states for jQuery.ajax error handler functions:
Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
It is related to the technique of JSONP where the actual request is injected as a <script> tag. So a standard jqXHR object including an ajax error event isn't available. There's some plugin as workaround available. This plugin and solutions for dealing with network timeouts are discussed e.g. in this and this stackoverflow questions.
Try handling the error in the then (or use done() and fail() )
$.ajax({
//... code omitted ...
})
.then(
function (response) {
$.each(response, function (i, val) {
//do something with data
});
},
function (error) {
//do something with error
}
});