I have a web application that gets data with a get call. When it is called, it sets a static variable. After the call is complete I want to get the value, but the complete function that I call is not working, its calling it to fast because its null.
$.get('../Controls/myfullcontrol.aspx', {}, function (data) {
$('#SiteFullControl').html(data);
}).complete(function () {
$('#FullControlCount').html('Full Control (<%=GlobalClass.GlobalVariables.User.Count %>)');
$('#LoadingAjax').dialog('close');
});
Using Firebug or Chrome's Inspector, look at the XHR and ensure that the script is actually returning something.
Are you looking for data returned to the complete function?
Then you need a parameter in the function:
}).complete(function (data) {
You don't need the $.complete() method because the $.get() contains allready an success callback.
http://api.jquery.com/jQuery.get/
You could work with jQuery the Promise interface (introduced in 1.5).So you can chain multiple callbacks on a single request...
Take look: http://api.jquery.com/jQuery.get/#jqxhr-object
jQuery.get( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
$.get('ajax/test.html', function(data) {
//STUFF AT SUCCESS
});
Related
I have built a weather website that calls the flickr API 1st, then calls the yahoo API for the weather. The problem is that the data from the ajax call - from the yahoo API is not here in time for the page to load its content.
Some of the things I have used to try and slow the ajax call down:
setTimeout
wrapping the entire function that $.ajax(success: ) calls into another function, wrapping it in setTimeout
taking the callback function out of $.ajax(success: ), and putting into the $.ajax(complete: ) param
taking the data object that $.ajax(success: ) passes in, and copying that to another var, then going outside of ajax call and putting the function that handles the data inside of $.ajaxComplete(), passing new object var
There are more ways that I have tried to go about this, but I have been at it for 3 days and cannot find a solution. Can someone please help me here
Here is a link to the project
My Weather App On codeine.io
function RunCALL(url)
{
var comeBack = $.ajax({
url: url,
async: false,
dataType:"jsonp",
crossDomain: true,
method: 'POST',
statusCode: {
404: function() {console.log("-4-4-4-4 WE GOT 404!");},
200: function() {console.log("-2-2-2-2 WE GOT 200!");}},
success: function(data){
weatherAndFlickrReport(data);},
error: function(e) {console.log(e);}
});
}
Are you using jQuery? If so, you have to chain your callbacks. Which, at a high level, would looks something like:
//You might want to use .get or .getJSON, it's up to what response you're expecting...
$.getJSON('https://example.com/api/flickr', function(response) {
//This your callback. The URL would end up being https://example.com/api/yahoo/?criteria=lalalalala
$.getJSON('https://example.com/api/yahoo/', { criteria: response.propertyYouWant}, function(yahooResponse) {
//Do something with your response here.
});
});
Edit: I have updated your snippet with a working solution (based on the above AJAX requests) which now shows both your JSON objects ready for consuming. Looky here.
Currently I am translating my ajax calls to regular $.pjax() call. Everything works fine but ajax success function. I can't manage how to call pjax success function with given parameters.
The only thing I can use is defining pjax global success function to be called on each pjax call:
$(document).on('pjax:success', function(event, data, status, xhr, options) {
});
But unfortunately I would like to define per call specific success function.
Ajax call example:
$.ajax({
url:"/myPage/myFunction",
type:"POST",
data:giveMeData(),
success:function(data){$('#right_form').html(data);console.log('Success works!')}
});
Pjax call example:
$.pjax({
url:"/myPage/myFunction",
type:"POST",
container:'#right_form',
data:giveMeData(),
success:function(){console.log('Success works!')}
});
I don't believe that the jQuery PJAX library supports passing a "success" function directly in to a $.pjax call, although I suspect you could work around this using the $(document).on('pjax:success') callback & its options attribute in order to achieve the same functionality.
For example, say your request is like the above, but you want to have a custom success callback you could use something like this:
$.pjax({
url:"/myPage/myFunction",
type:"POST",
container:'#right_form',
data:giveMeData(),
custom_success:function(){console.log('Custom success works!')}
});
Then, in order to run the custom_success method you could hook up the standard pjax success listener, and given that all the parameters provided to $.pjax are made available in options, you can then grab custom_success function and run it. So your listener may look something like example
$('#right_form').on('pjax:success', function(event, data, status, xhr, options) {
// run "custom_success" method passed to PJAX if it exists
if(typeof options.custom_success === 'function'){
options.custom_success();
}
});
Which i *think* would provide the sort of functionality your after?
A late answer but I found the solution here.
$.pjax({
url:"/myPage/myFunction",
type:"POST",
container:'#right_form',
data:giveMeData(),
}).done(function() { console.log('Success works!') });
I've built a web application that makes heavy use of the jQuery.ajax() function on dozens of different pages. Naturally, each use of jQuery.ajax() is passed a configuration object with a function to serve as the callback for the 'success' property.
I've now run into a situation where I would like to globally perform a certain action on multiple pages if the server returns a certain error code for any given ajax request. I'm thinking about somehow overriding a part of the jQuery library by including javascript in the header of my pages which would perform a conditional check operation, and then continue to execute whatever callback function was passed in the configuration object. Is this possible? I'm currently reviewing the source for the jQuery library to see if I can do this.
I think you need to look at the Global Ajax Event Handlers.
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
In jQuery 1.5+ , you can accomplish this via the converters option for $.ajax. Normally, the converters are just supposed to convert data received form the web server, and pass it off to the success callback, but you can run other code in there if you want.
Drop this code into a js file that is embedded on all of your pages.
$.ajaxSetup({
// the converter option is a list of dataType-to-dataType conversion functions
// example: converters['text json'] is a function that accepts text and returns an object
// note: to redefine any single converter, you must redefine all of them
converters: {
"text json": function (text) {
// NOTE: this converter must return a parsed version of the json
var result = jQuery.parseJSON(text);
if (result.errorMessage) {
// catch the error message and alert
alert(result.errorMessage)
}
return result;
},
"text html": true,
"* text": window.String,
"text xml": jQuery.parseXML
}
});
Full example:
http://jsfiddle.net/waltbosz/8a8fZ/
I ended up overriding the success callback in a global manner using $.ajaxSetup, like this:
$.ajaxSetup({
beforeSend: function(xhr, options) {
var originalSuccess = options.success
options.success = function(data, textStatus, jqXhr) {
// trigger some sort of event here for interested listeners
originalSuccess.apply(this, arguments)
}
}
})
i have script like this.
function getContactLastDateOfDeparture(contactId) {
$.get(
'/transaction/ajaxGetContactLastDateOfDeparture/'+contactId,
'',
function(data){
alert(data);
return data;
},
'json'
);
}
I test script above with console.log(getContactLastDateOfDeparture(2144)), when in alert phase it outputted string 2011-12-06, but when phase return it outputed undefined
How to make the return should be 2011-12-06 ?
You can't really do a return in an AJAX function, as it is asynchronous. It is better to call another function at the end if you want to pass along the value.
To do this, you can pass it along like this:
function getCall(param, callback) {
$.get('url', function (data) { alert(data); callback(data); }, 'json');
}
If you really want your function to return value from the ajax call, you can use $.ajax instead of $.get (essentially $.get is based on $.ajax with some simplified params); $.ajax has a parameter "async" that you can set to false to make the ajax call synchronous.
IMPORTANT - it is not recommended to use sync calls with ajax as it will freeze the js execution and might lead to unexpected problems.
http://fixingthesejquery.com/images/ajax101.png
You should read up about Ajax, asynchronous behavior and event driven programming. It just doesn't work like that.
Gus,
The first parameter is a url to a valid processing page (html, asp, php, etc).
EDIT (after being voted down):
A valid url, in your case, would be:
$.get('url', function (data) {
alert(data);
});
your url '/transaction/ajaxGetContactLastDateOfDeparture/'+contactId would
not "compute"
However,
'/transaction/ajaxGetContactLastDateOfDeparture/getContactID.php?contactID='+contactId
would!
Your processing file (.asp, .php, etc) would, then, return the value you are
expecting.
Is there a way that I can access the data I receive during success so i can use it during the complete callback?
Or perhaps there is a way where i can assign multiple success functions?
What i need is, to allow success callback to be changed based on situation, but I need to always perform a dedicated function on success using the same data that was returned to the first function.
I suppose i can always setup my call like so, but i'm looking to see if there is a better way.
CallServer = function(options) {
if(options.success) {
var customSuccess = options.success;
options.success = function(data) {
defaultSuccess(data);
customSuccess(data);
}
}
$.extend(true, defaults, options);
$.ajax(defaults);
}
EDIT: I have found my answer. I didn't realize that the xhr holds the data as the responseText. so the following gets me the same thing that gets returned as 'data' on success.
complete: function(xhr){dosomething(xhr.responseText);}
and that's it! Thanks
In jQuery, the success callback accepts the data as its first argument.
From the jQuery Documentation ( http://api.jquery.com/jQuery.ajax/ ) the argument list for the success callback is:
success(data, textStatus, jqXHR)
As far as I am aware, there is no built-in way to add multiple success callbacks, but you could easily dispatch any number of functions from a custom success callback.
Perhaps you could use a system like:
function customSuccess(data) {
if (situation == "one way") {
firstFunction(data):
}
else if (situation == "another way") {
secondFunction(data);
}
}
I have found my answer. I didn't realize that the xhr holds the data as the responseText. so the following gets me the same thing that gets returned as 'data' on success.
complete: function(xhr){dosomething(xhr.responseText);}
and that's it! Thanks