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.
Related
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.
I'm trying to write a js function that triggers another, variable, function when complete. I figured I could do this by passing the second function's name as a string, but I can't get it to work. Here's my code:
logMeIn('likeThisPost');
function logMeIn(callBack) {
//First function content
$.post("/ajaxurl/",
{
login_id: login_id,
intent: 'login'
},
function(){
console.log('Logged in, refreshing header');
$.post("/secondajaxurl/",{},
function(data){
//success
if(typeof callBack!=='undefined') {
window[callBack]();
}
}
);
}
);
});
}
This should, according to my thinking, run likeThisPost after successfully completing both ajax calls in logMeIn, but instead I get this error:
window[callBack] is not a function
The function I'm calling on success definitley exists, and besides which, it doesn't look like it's even trying to call that function, but it's treating callBack as literal rather than a string.
I'm using jQuery and have everything wrapped in a $. Where am I going wrong?
With thanks to Jonas W and Rory McCrossan, the answer was to change the passed function to the function name, rather than a string, and then call the function directly rather than using window.
So logMeIn(likeThisPost) instead of logMeIn("likeThisPost") and callBack(); rather than window[callBack]();.
Thanks!
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);
});
What I'm trying to do is to get a list of calendars from google, and then get the list of events from each calendar.
So basically I'm calling the events.list method within the callback function for the calendarList.list method.
However, when debugging using Firebug, it appears that the callback function for the events.list method just doesn't get called at all.
var request2 = gapi.client.calendar.events.list({
"calendarId":calendarId
});
request2.execute(function(response2) {
resp2 = response2;
findEvent();
});
I can debug up to request2.execute, but function(response2) is never performed.
resp2 is a global variable, and all of this code is in a function called from the first request's callback.
A very similar code works perfectly for the first call, with a different global variable.
I've tried removing either of the lines in the callback to no effect.
Thanks for any help.
I have gotten JSONP working with an anonymous function but can't get it to work with a named function. This code works (the alert appears with the correct data):
$.getJSON('http://example.com/test.aspx?foo=bar&callback=?',
function (data) { alert(data.baz) })
However this code does not work (no alert appears):
function dat(data) {
alert(data.baz)
}
$.getJSON('http://example.com/test.aspx?foo=bar&callback=dat')
Can you explain why the last code does not work?
EDIT: I took out a non-relevant example
I'm not sure that leaving out the callback is the correct usage (or, at least, I cannot find any documentation that defines what should happen if a callback is not supplied). If you want to use a named function as the callback you can do:
function dat(data) {
alert(data.baz)
}
$.getJSON('http://example.com/test.aspx?foo=bar&callback=?', dat);
You should be able to meet jQuery half way with something like this:
$.getJSON('http://example.com/test.aspx?foo=bar&callback=?', dat);
After looking at jquery's ajax code a bit, I think what you want to do is either
do like Dave Ward and Hamish suggest, ie pass in the function. Or, I think you can pass the function's name as a string like this, since it is attached to the window and jquery looks at the type of the callback for determining behavior.
function dat(data) {
alert(data.baz)
}
$.getJSON('http://example.com/test.aspx?foo=bar&callback=?', 'dat');
Or, you can use getScript which will add the url as a script tag, which is fine for what you are trying to do.
function dat(data) {
alert(data.baz)
}
$.getScript('http://example.com/test.aspx?foo=bar&callback=dat');