I've seen lots of questions and solutions to problems like this but nothing has worked for me. I have this:
function() {
$("#bdiv").load("bosses.php #icc10n",function(){
return $("#bdiv").html();
});
}
But it's not working. To clarify, I want to load content into #bdiv and then return the contents of #bdiv. But it seems that $("#bdiv").html() is being returned before the content is loaded even though I've put it in a callback function.
$("#bdiv").load("bosses.php #icc10n",function(data){
// use the data param
// e.g. $(data).find('#icc10n')
});
as far as I know you cannot make a return statement in the callback function of a $.ajax(), $.post(), $.get(), etc.. method. You could, however, store the 'data' value in a variable declared outside the function, and then set the value of that variable when the callback function executes. And there is a variety of other options.
You can't do that.
AJAX is asynchronous, meaning that your function will return before the server sends a response.
You need to pass the value to your caller using a callback, the way $.load does.
Related
I've read the answers here and here that describe how to read the value of jQuery ajax settings. My question, however, is this:
if I have previously invoked the ajaxSetup function with settings, like $.ajaxSetup({cache: true}), and then I invoke $.ajaxSetup() (with no arguments), are there any side effects to this invocation?
Or more bluntly, does calling $.ajaxSetup() with no arguments do anything other than return a plain object that contains the settings for ajax?
The answers I've referenced above both call ajaxSetup in this way in order to read the value of a setting, and I have been unable to find any official answer on the jQuery docs that indicate what calling ajaxSetup with no parameters does, probably because its use is so heavily discouraged.
In my browser, I ran a simple test by loading jQuery, running $.ajaxSetup({async: false}); followed by $.ajaxSetup(); and found that the value of async was still unchanged (the default value is true, and so if calling $.ajaxSetup() resets the settings to default values, then the value of async should have been changed), but this probably isn't a strong enough evidence to conclude that side effects do not occur when the function is invoked in this way.
Does calling $.ajaxSetup() with no arguments do anything other than return a plain object that contains the settings for ajax?
No.
Example
// set a new custom url
$.ajaxSetup({
url: 'CHANGED'
});
// call it again with no params
$.ajaxSetup();
// the url is still the custom url
console.log('url: ' + $.ajaxSetup().url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Why?
If we look at the code for ajaxSetup, we see that, when called with a single parameter, it returns the call:
ajaxExtend( jQuery.ajaxSettings, target );
where target is the single argument you passed into ajaxSetup().
Now, inside ajaxExtend, we can see that it tries to iterate over that same argument with a for in loop.
Relevant code:
function ajaxExtend( target, src ) {
for (var key in src) {
// here is where target, which in this case is jQuery.ajaxSettings, gets overriden
}
return target;
}
Since you don't pass anything, basically you are doing
function ajaxExtend( target, src ) {
for (var key in undefined) {
// this is never reached
}
return target;
}
which never enters the for in loop and returns the current value of jQuery.ajaxSettings.
I want to save the value of data and status in a variable and use it after the closing brackets of jquery GET/POST function.But alert comes only when it is inside .get braces.
$(document).ready(function(){
$.get("demo_test.asp",function(data,status){
v = data;
});
alert("Data:"+v);
});
As Jasper said, your alert is being triggered before the request is complete (async!). So, you have two options:
Do your logic inside the callback:
$.get("demo_test.asp",function(data,status){
v = data;
alert("Data:"+v);
//Process stuff here
});
Or pass the received data onto another function and work with it there
$.get("demo_test.asp",function(data,status){
v = data;
doStuff(v);
});
function doStuff(param) {
console.log(param);
}
You're absolutely correct; the code is working as it should... here's why:
The page loads and starts running code, it then hits the .get command and then keeps running, obviously making it to the 'alert' you have next. Since the .get function is still working on fetching the data before your page makes it to the 'alert' part... there's nothing to prompt.
You might want to string things together after the .get, using deferred objects. Look into: http://api.jquery.com/deferred.always/
This is a way of tacking on another function inside of the one fetching your data, so they depend on each other.
Simple answer, yes, you can store the data in a global variable and access it elsewhere. However, you must wait until it is ready.
The better way to do it is to instead store the jqXHR globally and simply add a done callback to it when you need to access the data.
var reqDemoTest = $.get(...);
//... some time later...
reqDemoTest.done(function(data){
console.log(data);
});
I'm a javascript noob, and I don't understand why this works:
$().load('/my/url/', {my:data, more:data}, jsFunc());
function jsFunc()
{
$("#myid").val("yep");
}
But not this:
$().load('/my/url/', {my:data, more:data}, function() {jsFunc()});
function jsFunc()
{
$("#myid").val("yep");
}
I tried an $.ajax instead of $.load with the same result. I will be passing the response data to jsFunc() and that is why I need jsFunc() inside the function. I'm sure it is something simple I'm just not very experienced with javascript. Thanks.
Thanks again for all the help. I decided to use $.post because it works best for the situation but now I'm having trouble with the response data. My code looks like this:
$.post('/my/url/', {my:data, more:data}, function(data) {
var strung = JSON.stringify(data)
var parse = jQuery.parseJSON(strung)
console.log(parse.some);}, 'json');
I'm logging to the console to see what is coming back for now and I will add the callback when I see the correct value logged. The process I got from the jQuery api page, but it will only log undefined. When I change parse.some to parse the console log will display the objects and I can select an element and see the correct key:value pair. Any help would be sweet.
Neither works. The first one appears to work, because you call the function jsFunc immediately, it doesn't wait for any response.
If you create an empty jQuery object using $() and use the load method on that, it won't call the server because there is no element where it can put the result.
To specify the callback function you either use the name of a function:
$('#someElement').load('/my/url/', {my:data, more:data}, jsFunc);
or a function expression:
$('#someElement').load('/my/url/', {my:data, more:data}, function() { jsFunc(); });
The first code block will simply call jsFunc() and return the results as the parameter to the load(..) method, which is odd because that parameter is supposed to be a callback function to fire when the load completes, but that works? The callback syntax is more in keeping with the second example (the one I believe you stated doesn't work).
Answer to my second part:
My returned JSON data consisted of many objects, so I had to specify the index and the key to get the value to return.
I have a coding difficulty which have been asked in this forum before:
Calling a JavaScript function returned from an Ajax response
But I didn't find the answers quite satisfying. To be more precise of the problem I'm dealing, here is the detail:
I dynamically load a document (HTML and javascript) using jquery
var url = 'document.php';
$('#container').load(url);
Example of what the document.php looks like:
<form>
<input name="firstname"></input>
</form>
<script>
function dosomething()
{
console.log($('input[name=firstname]').val());
}
</script>
*The dosomething() function is the one I'd like to call later
And then I want to call the functions from that document.php. Due to my requirement, I don't want to call the function after the documents' loaded, but rather to call it later when I need it. Because it was dynamically loaded, the DOM doesn't recognize the functions. How to properly call this function?
Thank you
the DOM doesn't recognize the functions
This sounds like your other functions are wrapped in $(document).ready() in the remote page. If that is the case they are out of scope for you to call them from code in the main page and you need to move them out of the ready handler to make them globally accessible.
EDIT: Other possibilities
Script tags in head- move to body after html, or use $.getScript in ajax callback to retrieve
I think that you're trying to implement the technique called on-demand javascript (or lazy-loading). In other words, your page should initially load just a small script - but use a bunch of objects and functions, which are available in some other files, but will be loaded when they're required.
If that's the case, I have to warn you: you'll probably need to update your existing code. Instead of just calling some function right as it is, in all gun-blazing glory, you should check for its existence first - and if it's not available, wait for its loading:
if (typeof lazyObjects.someLazyFunction !== 'function') {
lazyLoad('lazyFunction.js');
}
lazyObjects.someLazyFunction();
The key point here is that lazyLoad should be synchronous. In other words, you'll have to wait until the script containing your function is actually loaded. Otherwise someLazyFunction just won't be defined when it's called, even with this sort of checks.
lazyFunction.js, in turn, will contain some code that will alter lazyObjects, adding to them the required method as a property:
// in lazyFunction.js
lazyObjects.someLazyFunction = function() { ... }
While it's technically possible to use global (=window) object for these cases, I usually don't do this - and won't recommend doing it either.
See, it's not that simple. ) I'd recommend reading this article to find out more about this technique - and actually using some established components to implement it in your code (some of them are mentioned in the linked article).
I want to call a Javascript function from Flash, which I can do with ExternalInterface, but the Javascript function takes a callback. Is there a way to give it a Flash callback?
I've thought of something like this:
ExternalInterface.addCallback("foo", function(){...});
ExternalInterface.call("theFunction", "foo");
But that wouldn't work since theFunction would attempt to do foo(), while it should really do swfObject.foo(). The problem is the page and its Javascript are not under my control (though I can request changes if really needed).
This is closely related to the first question in the related questions section.
Along the same lines as the answer to that question, you can do:
ExternalInterface.addCallback("foo", function() { /* ... */ }); // The callback
ExternalInterface.call("theFunction(function() { swfObject.foo(); })");
You're misunderstanding the documentation, I think. callback in this instance is just a reference to a function inside Flash, not a callback to something you call.
Basically, you use .call() to call a JS function from AS; and you use .addCallback() to tell the Flash Player which AS function should be called based on the name.
On your example, theFunction would get one parameter as being 'foo', which is the name that references your anonymous AS function. Not sure why you would want to pass the function like that, but if you need, you could just call it from JavaScript with
function theFunction(callback) {
// .. do something...
swfObject[callback]();
}
Now, if you don't have control over the JS/HTML side, I'm not sure if you can do that. Not sure why you'd need, anyway - JS calls are synchronous, as if they were running on the same thread, meaning the Flash Player will execute the JS code and only then return to the Flash Player... you don't have to wait for execution or anything.
Also, if you really need to control the page without touching the JS/HTML side, remember you can inject entire pieces of JS code via .call - it doesn't need to be a simple function call. You can create your entire functions from inside the SWF. For example,
var js:XML = <script><![CDATA[
// Javascript code...
]]></script>;
ExternalInterface.call(js);
Or, if you need the return data, you don't need a callback either - just do a simple call as in
// JS
function isNumberZero(__num) {
return __num == 0;
}
// AS
trace ("Is number zero = " + ExternalInterface.call("isNumberZero", 10));
Not sure if this helps at all. If not, it'd be good to have more information on what exactly you're trying to do.