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/
Related
This question already has answers here:
window.onload vs $(document).ready()
(17 answers)
Closed 2 years ago.
What is the order of execution for the below sample code? Will $(window).on('load', function () { }) be executed before completing $(document).ready(function () { });.
I need to change all the text field values to uppercase after loading values form server through AJAX call. This page has more than twenty fields.
//Sample Code
$(window).on('load', function () {
//Some Code... to change all text field values to uppercase
alert("Window Loaded");
});
$(document).ready(function () {
//Some Code....
$.ajax({
url: "TestLoadOne",
type: "POST",
async: false,
contentType: 'application/text; charset=utf-8',
success: function (data) {
console.log('async false Ajax');
}
});
$.ajax({
url: "TestLoadOne",
type: "POST",
async: true,
contentType: 'application/text; charset=utf-8',
success: function (data) {
console.log('async false Ajax');
}
});
$.ajax({
url: "TestLoadOne",
type: "POST",
async: true,
contentType: 'application/text; charset=utf-8',
success: function (data) {
console.log('async false Ajax');
}
});
alert("Document Loaded");
});
//C# Code.
public string TestLoadOne()
{
System.Threading.Thread.Sleep(40000);
return "Hello";
}
Because your AJAX calls are asynchronous, there isn't really telling in what order they will finish. What we do know is that the calls will be fired off inside document.ready before window.onLoad is called (see for details). Ideally you should write your callbacks such that their order doesn't matter.
it depends, for your case you are using $.ajax, if you set the async to false, it will wait for the $.ajax until it finishes and return a response, but if you set it to true it will not wait:
async: false,:
//Sample Code
$(window).on('load', function () {
//Some Code... to change all text field values to uppercase
alert("Window Loaded");
});
$(document).ready(function () {
alert("Document Loaded");
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/1",
type: "GET",
async: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log('async false Ajax');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
async: true,:
//Sample Code
$(window).on('load', function () {
//Some Code... to change all text field values to uppercase
alert("Window Loaded");
});
$(document).ready(function () {
alert("Document Loaded");
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/1",
type: "GET",
async: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log('async true Ajax');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Will $(window).on('load', function () { }) be executed before
completing $(document).ready(function () { });.
The answer is "Yes".
$(window).on('load', function () { }) will be executed AFTER $(document).ready(function () { })
However, since there are asynchronous operations are involved here (AJAX), they will be completed after $(window).on('load', function () { }) gets executed.
Even inside $(document).ready(function () { })
alert("Document Loaded"); will execute before the AJAX request is processed.
Let's mimic this:
function A(){ //Similar to document.ready
setTimeout(()=>{
alert("hello from setTimeout") //similar to Ajax request
}, 0)
alert("hello from A")
}
function B(){
alert("Hello from B") //Similar to window.load
}
function C(){ //Any other function in the script executing after window.load
alert("Hello from C")
}
A();
B();
C()
You notice that setTimeout gets executed after all of these methods execution get finished.
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.
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();
});
I have this problem where not all of my ajaxComplete calls are getting fired.
My Code
$(document)
.ajaxStart(function () {
$.blockUI();
})
.ajaxComplete(function () {
$.unblockUI();
});
Here's the code where ajaxComplete didn't fire :
$('body').on('click', '.actTimeSheetApprove', function () {
var node = $(this).parents('tr');
$.ajax({
url: '/TimeSheet/Approve/',
type: 'POST',
context: this,
data: {
__RequestVerificationToken: fnGetToken(),
id: $(this).data('id')
},
success: function (data) {
if (data == 'success') {
var table = $('#tblTimeSheetApprove').DataTable();
table.row(node).remove().draw();
console.log('SUCCESS'); //I already made sure this is called
}
}
})
})
Note that I already make sure SUCCESS log is called.
Any idea why?
UPDATE :
Here's my controller
[HttpPost]
[ValidateAntiForgeryToken]
[ClaimAuthorize("Role", "Manager")]
public ActionResult Approve(int id)
{
_uow.TimeSheet.Approve(id, User.Identity.Name);
_uow.Save();
return Content("success");
}
And here's my console log :
I guess that you have incorrect the "syntax" in the $.ajax call, you miss the complete...
success !== complete
https://api.jquery.com/Ajax_Events/
With ajaxStart you can use load or ajaxSetup for make the request and define the behaviour of the success/error methods;
Also for debug, try to ajaxStop() and see if everything works well.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8. In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown). This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
please check this link : firing in Ajax call
I am trying to call an ajax function inside the success function of a function.
This is my code:
success: function () {
jQuery.ajax({
type: "POST",
url: "script.php?subtype=3",
data: "page=1",
beforeSend: function () {
jQuery(".data").animate({opacity: 0.2}, 150);
jQuery(".outer-data").css({'background': 'url("ajax-loader.gif") no-repeat scroll 50% 50%'});
},
success: function (msg) {
jQuery("#container_cat").ajaxComplete(function (event, request, settings) {
jQuery(".outer-data").css({'background': 'none'});
jQuery("#container_cat").html(msg);
});
}
// ...
});
}
Even though I get the response in Firebug console from
jQuery("#container_cat").html(msg);
I don't get any output in the document.
What am I missing here?
success: function () {
jQuery.ajax({
type: "POST",
url: "script.php?subtype=3",
data: "page=1",
beforeSend: function () {
jQuery(".data").animate({opacity: 0.2}, 150);
jQuery(".outer-data").css({'background': 'url("ajax-loader.gif") no-repeat scroll 50% 50%'});
},
success: function (msg) {
jQuery(".outer-data").css({'background': 'none'});
jQuery("#container_cat").html(msg);
}
// ...
});
}
Seems like the problem is that you are calling the ajaxComplete() function inside the success function. You dont need to use ajaxComplete inside success function as success function will only be executed when the ajax request is completed and succeeded. So theres no sense of using ajaxComplete inside it.
For reference : ajaxComplete docs
You can use ajaxComplete before success function.