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
Related
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!
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 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');
},
});
After reading various examples on stackoverflow I wrote this function :
function showGetResult(crossDomainUrl) {
$.ajax({
url: crossDomainUrl,
type : 'GET',
crossDomain: true,
success: function (data) {
debug(data);
return data;
}
});
}
and called it using this
alert(showGetResult(crossDomainUrl));
But all I get is 'undefined', this is being used in a web-browser extension inside a content-script.
This is because the Ajax request runs asynchronously. The return data doesn't do anything. You could change it to (updated to reflect the request in the comments to be able to download a script):
function showGetResult(crossDomainUrl) {
return $.ajax({
url: crossDomainUrl,
type : 'GET',
dataType: 'script',
crossDomain: true
});
}
showGetResult('http://code.jquery.com/ui/1.10.3/jquery-ui.js')
.done(function(data) {
alert("success: " + data);
})
.fail(function(jqXHR, textStatus, ex) {
alert("failed: " + textStatus);
});
For the call actually to work cross-domain, you will need to use jsonp or script. Read this wiki for more information about Same-origin policy. Refer to this answer for more information about using jsonp.
The code above will inject the downloaded jscript in the dom and execute it.
The $.ajax() set up the query, and return immediately, so the function returns before the request is completed. Specify a function to call on completion of the query using success.
function showGetResult(crossDomainUrl) {
$.ajax({
url: crossDomainUrl,
type : 'GET',
crossDomain: true,
success: showData
});
}
function showData(data){
debug(data);
return data;
}
showGetResult(crossDomainUrl);
see http://jsfiddle.net/5J66u/8/ - (updated to specify jsonp and a better URL for it)
Let's say for example, I have the following javascript function that returns a boolean:
function CallWebServiceToUpdateSessionUser(target, user)
{
var dataText = { "jsonUser": JSON.stringify(user) };
$.ajax({
type: "POST",
url: target,
data: JSON.stringify(dataText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
return true;
},
failure: function (msg)
{
return false;
}
});
}
and the target function on the server that is being called could take up to... 15 seconds to respond.
How do I guarantee that this function will not exit until after the server call has been completed? Or, how can I guarantee that who ever is calling this function will get a true/false and not an undefined?
NOTE:
I've seen people use async: false but that hangs the UI which I do not want.
See http://api.jquery.com/jQuery.ajax/. You need to do an AJAX request with async: true to your parameters. You will then need to edit your code so the code that executes after a successful request is inside the successful block.