ajaxComplete not firing - javascript

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

Related

Ajax callback to check variables as global

I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!

Error handling for Remote Autocomplete is not working

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
}
});

Is there a way to add an OnSuccess script to my Ajax call

I have the following script:
$.ajax({
url: '/Switch/showOptions',
data: {
switchid: "331",
},
type: 'get',
success: function (html) {
$('#showoptions').html(html);
$("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
OnSuccess('createsuccess')
},
});
What I am trying to do is to fire an OnSuccess script after showing the dialog, currently I am getting an exception that OnSuccess is not defined? So can anyone advice how I can fire an OnSuccess script for my Ajax call?
Try this using jQuery.when() as described in this answer here:
Provides a way to execute callback functions based on one or more
objects, usually Deferred objects that represent asynchronous events.
So with that in mind, here is your code reworked to use jQuery.when():
var ajax_action = $.ajax({
url: '/Switch/showOptions',
data: {
switchid: "331",
},
type: 'get',
success: function (html) {
$('#showoptions').html(html);
$("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
},
});
$.when(ajax_action).then(function(data, textStatus, jqXHR) { OnSuccess('createsuccess'); });
Or if you just want to test this concept, change the jQuery.when() to be this:
$.when(ajax_action).then(function(data, textStatus, jqXHR) { alert('I am a success!'); });
EDIT: Last edit to try and address original posters request. They want to fire a script called createsuccess, so just do this:
$.when(ajax_action).then(function(data, textStatus, jqXHR) { createsuccess(); });
Your code should work if you add a ; after your OnSuccess call. This isn't an event to be fired but it is a a function that will be executed after the first two statements.
function OnSuccess(p_Success) {
alert('it worked!');
}
$.ajax({
url: '/Switch/showOptions',
data: {
switchid: "331",
},
type: 'get',
success: function (html) {
$('#showoptions').html(html);
$("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
OnSuccess('createsuccess');
},
});

Two Ajax onclick events

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
}

How to initiate a function when $ajax() is called?

In jquery that is.
I would like something that works as the success-pararameter, but that is run when the function is called, rather than once I get the response.
sample (oajax is an extension of ajax for open auth)
$.oajax({
url: url,
jso_provider: "facebook", // Will match the config identifier
jso_scopes: false, // List of scopes (OPTIONAL)
dataType: 'json',
success: function(data) {
fbposts=data.data
//a bunch of code irellevant for the question
},//success done
error: function() {
console.log("ERROR Custom callback()");
}
})
};
Are you looking for .ajaxSend() ?
Attach a function to be executed before an Ajax request is sent.
This function (and .ajaxComplete et al) allow you to register callback functions that are called for the different phases of every AJAX request.
In a normal ajax function, you pass it as beforeSend:
$.ajax({
url: url,
dataType: 'json',
beforeSend: function(jqXHR, status){
// CODE HERE
},
success: function(data) {
fbposts=data.data
},
error: function() {
console.log("ERROR Custom callback()");
}
})
};
You'll have to check if oajax have this event too, but it probably do

Categories