I have used $.ajax function to fetch data from C# in asp.net MVC3.0, Now I want is to get the value from the success function of $.ajax and used it in another function defining global variable and putting the result in it is not working so please let me know how can I get the value.
Invoke a callback function from within the success function. Most likely you are treating everything as synchronous when infact Ajax is asynchronous.
Low down dirty way would probably be to specify async:false
Related
$.getJSON("../../index.php/churchlocator/base", function(data) {
base_url = data.base;
});
alert(base_url);
How can I get base_url in the above code to be accessible outside of the getJSON var?
The right answer here is to put all code that references the result of the ajax call in the success handler for the ajax call. Do not use global variables for this:
$.getJSON("../../index.php/churchlocator/base", function(data) {
var base_url = data.base;
alert(base_url);
// or you may call some other function here and pass it the data
myFunction(base_url);
});
Ajax calls are "asynchronous" (that's what the A in Ajax stands for). What that means is that they complete sometime in the future and your other javascript continues running. When they complete, they will call their success handler. As such, the ONLY way you can know when the data has been returned from the Ajax call is by either placing code inside the success handler to operate on the returned data or by calling a function from that success handler and passing it the data.
This is asynchronous programming and you MUST use this model if you program with asynchronous functionality of any kind. You cannot use traditional sequential programming with asynchronous function calls.
The code is very complex so i have simplified below in order to confirm if the behavior i am experiencing is normal or due so some other error i have made in the code.
I have two separate ajax requests that each have their own unique call back. I do not care which one completes first and one has no dependency on the other
function ajax(url, cbS){
$.ajax({
url: url,
contentType: 'application/json',
dataType: 'json',
success: function(data){
cbS(data)
},
});
}
function callbackSuccess1(data){
$('#div1').html(data)
}
function callbackSuccess2(data){
$('#div2').html(data)
}
//request#1
ajax(myapiurl+'&peram1=100', callbackSuccess1);
//request#2
ajax(myapiurl+'&peram2=200', callbackSuccess2);
The problem: Sometimes callbackSuccess1 gets the data intended for request#2 and vice versa.
It seems that which ever request completes first fires callbackSuccess1 and the second to complete fires callbackSuccess2.
I need the callback to be bound to it's specific request so that regardless of the order in which they complete each request fires it's proper callback.
OTHER INFO: My backed is django-tastypie, at this point i am thinking that tastypie is somehow messing up the response. That is the only logical conclusion, given that the javascript seems to be immutable.
The proof that this is actually occurring is that when i inspect the responce on request#1 the data objects are clearly intended for request#2...
CONCLUSION:
Thanks for confirming that 'each invocation of your ajax() function will create it's own closure'. This was what i thought was going wrong. I found the problem in my API. I was doing some funky stuff and it looks like I had a variable that was not getting trashed in time causing the API to return the wrong data if the first request took longer than the second.
The only issue I see with the code you have included is that the function argument is cbS, but you are calling cbs(data) - note the different capitalization.
Other than that, each invocation of your ajax() function will create it's own closure and have it's own arguments and those arguments will be preserved separately for the internal success callback. This is an important capability in javascript and it works. It does not get the arguments of one call confused with the callback of another as long as you are not using any global variables or state that might change during the execution of the asynchronous ajax call.
You could probably use jsonp and specify callback query parameter in URL for $.ajax
callback would be the name of javascript function which is to be invoked whenever the response is returned from server.
For more details please refer jquery doc : http://api.jquery.com/jQuery.ajax/
For theory : http://en.wikipedia.org/wiki/JSONP
This is mainly used for cross-site ajax calls.
so I've been messing around with some Jquery Ajax promises/deffers etc... and i've come across something I don't completely understand, not strictly related to the Jquery Ajax.
I have always declared and called functions like so:
function foo1() { //sets function
alert('foo1');
}
foo1(); //calls function
But it seems the more I see different code a lot of people are declaring functions like the following, I just copied and pasted an example I saw so I would't miss anything:
var promise = $.ajax({
url: "/myServerScript"
});
promise.done(myStopAnimationFunction);
I understand what the above does, just an example.
The question is, is it better to assign functions to variables? What are the pros/cons, and in what situations is this way used?
At what point in this code is the actual function called. Does
promise.done(myStopAnimationFunction);
call both the ajax function, and then the callback, or just the callback?
Thanks
In your example, you're assigning your promise variable to what $.ajax returns (which is a jqXHR object)
var promise = $.ajax({
url: "/myServerScript"
});
Your then saying that once it's done, you want to call myStopAnimationFunction. Because $.ajax is async by default, the browser will skip right over this and only call your myStopAnimationFunction when the request is complete.
promise.done(myStopAnimationFunction);
Now, with your myStopAnimationFunction; you could always just do the following:
promise.done(function(){
$('.loader').hide();
});
but if you have code which you'll be using a lot, put it in a function so you don't need to repeat yourself (see DRY) - this has nothing to do with jQuery, however.
Your example is exactly the same as doing:
$.ajax({
url: "/myServerScript"
}).done(function(){
$('.loader').hide();
});
Those are two very different things! The first one is a function declaration. The second one is a function invocation, and what is assigned to the promise variable is the value returned by the function you're calling ($.ajax).
In any case, it is possible to assign functions to variables too (but I'm not sure if that's what you're really asking – if it is, this is a duplicate of var functionName = function() {} vs function functionName() {}).
Does promise.done(myStopAnimationFunction);
call both the ajax function, and then the callback, or just the callback?
Neither. That line is a call to done on the promise object, to register a callback to be called when the ajax response arrives. At that point you call done, the ajax request may have already fired, and the response even might already be available (if that's the case, the callback will be called immediately).
Imagine this scenario:
I have a link that fires up a JavaScript function(has an Ajax request in it).
The JavaScript function has a parameter passed by the link's onclick='jsFunction(param)'.
The JavaScript function sends the parameter value in a function inside a controller that sets the param value to a session variable.
The function in the controller will then send the new value of the session variable back to the JavaScript function's Ajax request.
When the data reached into the Ajax request, another function will be called using the data being passed.
Question:
Since I am talking about the session variable's value being passed to an Ajax request, how can I process the data came from the link to the second function in real-time? I want to post the code here but it's too verbose with the info I only need.
The current state of my code is that, I can't fetch the right/latest data. Instead, I get the previous data came from the previous link I clicked.
Is there an Ajax feature that I can only proceed to the next function if the first function is done processing the latest data?
Any help will be much appreciated.
You can use the callback to any of the jQuery AJAX methods to delay execution of another function until after the request is complete.
$.post('/some/url', somedata, function(returnData) {
// put the code you want to execute on completion here
});
or If you have already defined your function to be called after returning data, you can just write like this:
$.post('/some/url', somedata, processData);
i set up a webservice thats cross domain and needs to be contacted via json with padding
on a simple jquery codeline like this, i am successfull getting back json data.
$.getJSON("http://server/series/hist?jsonp=?", function(data){
console.log(data);
});
the webservice, will wrap the result in a function, whenever "jsonp" exists within in the url.
for those cases i used a default function name like:
myfunction({"a":1})
jquery helps me out here, and trys to call the function, that isnt existing ("myfunction()"). what i am trying to achieve instead is a simple call of the callback function (see above), to handle the data locally.
can you point me in the right direction?
thank you
I'm not quite sure what your problem actually is, but:
Interpretation 1
Assuming that by "locally" you mean "without using a callback":
That is impossible. JSON-P cannot work synchronously as it depends on the addition of a <script> element (which won't be processed until the current function has finished executing).
Interpretation 2
Assuming that by that isnt existing ("myfunction()") you mean "Your webservice always uses the function name myfunction:
Fix the webservice. jsonp=? means "Randomly generate a function name and pass it as the jsonp parameter.
The webservice must use that parameter to determine the function name used, and not use a fixed value such as myfunction.
Interpretation 3
You don't want to use JSON-P as the input, but to call your anonymous function directly.
You can't. It isn't stored anywhere you can access it. You have to rewrite your code so it isn't passed directly to getJSON:
function myFunction(data){
console.log(data);
}
$.getJSON("http://server/series/hist?jsonp=?", myfunction);
myfunction({"a":1})