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.
Related
I'm trying to stop my setInterval() call. The best would be to identify whenever my AJAX request is fulfilled. So, If I got my AJAX GET response, then clearinterval().
$(document).on('submit', '#post-form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/send',
data: {
room_name: $('#room_name').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
//alert(data)
}
});
$(document).ready(function com() {
loop = setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
//SOME CODE//
},
error: function(response) {
//SOME CODE//
}
});
}, 1000)
setTimeout(clearInterval(loop), 10000);
})
});
I tried to set a timeout, but it is very imprecise as it may take longer/shorter than the delay. So I would need something like if GET successful {clear interval()}
You need to move the clearInterval() call into the success callback of the AJAX call. You'll also need to move the loop interval higher up in your code so that it can be referenced from the success callback.
I'm also not sure why the loop interval is wrapped in a $(document).ready() call, because you can be assured that the document is ready if it is submitted. Also, the variable loop is awfully ambiguous. Try using the name of the API endpoint instead, like traffic.
Try this code:
$(document).on('submit', '#post-form', function(e) {
e.preventDefault();
const traffic = setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
clearInterval(traffic);
},
error: function(response) {
//SOME CODE//
}
});
}, 1000);
$.ajax({
type: 'POST',
url: '/send',
data: {
room_name: $('#room_name').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
// some code
}
});
});
Can I ask you first why did you use setInterval on this HTTP request ? You are probably using more computation power than you need.
You should probably make the request async (e.g https://petetasker.com/using-async-await-jquerys-ajax)
If you want to wait for an event to appear, you may want to have a look at web sockets (https://www.tutorialspoint.com/websockets/index.htm)
I have an asynchronous problem and for solve it I think I must use a callback. I want to execute some code after the code that is inside of the click() function finishes. How can I do that?
$("#mybutton").click(function() {
$.ajax({
type: 'GET',
data: {
accion: "get_option_child",
id: id
},
url: 'webservices.php',
success: function(data) {
var json = JSON.parse(data);
// some code
}
});
});
Just add a call to your desired function at the end of the success handler for ajax:
$("#agregar_opcion").click(function() {
// ...
$.ajax({
// ...
success: function(data) {
// ...
functionThatRunsAfterAjaxSuccess();
}
});
});
function functionThatRunsAfterAjaxSuccess() {
// gets called once the ajax call happening on click is successful
}
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 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/
So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}