I've been pulling my hair out with this function. It's a function within a function which is why I think it's not returning anything, heres the code:
function getEventImageNormal(data) {
$.getJSON("https://graph.facebook.com/fql?access_token=" + access_token + "&q=SELECT pic FROM event WHERE eid=" + data, function(data){
console.log(data.data[0].pic);
return data.data[0].pic;
});
}
The correct item, the URL of the image, is being set to the console log, but not being returned?
If anyone is wondering why I'm not using https://graph.facebook.com/object_id/picture to get the events image, it's because this functionality is currently not working and the only method is to use FQL for event images.
By default getJSON() performs asynchronous call.
You can call a function right within the success callback handler to treat the response.
$.getJSON("https://graph.facebook.com/fql?access_token=" + access_token + "&q=SELECT pic FROM event WHERE eid=" + data, function(data){
console.log(data.data[0].pic);
getResponse(data);
});
function getResponse(data) {
// handle your data here.
}
You need to add callback=? parameter to your url to let remote url and jQuery know it is a jsonp call. If it is only json sent, it is against cross domain security policies and browser won't accept it into the DOM.
This is in addition to processing the data within the sucecss callback of request, due to asynchronous nature of ajax.
var data=/* your value*/
$.getJSON("https://graph.facebook.com/fql?callback=?&access_token=" + access_token + "&q=SELECT pic FROM event WHERE eid=" + data, function(data){
/* process data here*/
})
Related
I am using jQuery.post a lot in my project and every time the browser sends a post request, I want to show a preloader while the request is in process and then stop the preloader when i get the reply form the server:
var params = {'action':'get_customer_info', 'customerID':4};
preloader.start();
$.post('ajax/url', params, function(response){
preloader.stop();
responseHandler(response);
});
Instead of adding the preloader.start() and preloader.stop() lines every time I call jQuery's post, I'd like to bind/trigger events on before the jQuery.post as well on the success/fail handlers.
I know how to bind and trigger events in general, but I'm not sure how I would do this with the $.post and handlers.
How do I do this?
You could set up the global ajax events, that way the preloader shows on every ajax request
$(document).ajaxSend(function() {
preloader.start();
}).ajaxComplete(function() {
preloader.stop();
});
Or you could create your own post function
function post(url, params) {
preloader.start();
return $.post('ajax/url', params, function(response){
preloader.stop();
});
}
To be used like
post('ajax/url', params).done(function(response) {
responseHandler(response);
});
I'm making an AJAX call to a JSON page that grab variables to populate a playlist for an HTML5 music player. I'm trying to have it so the playlist data updates every minute since its grabbing the information from a radio. I also dont want it to refresh the player itself, only the playlist. Everything works great except I'm getting myPlaylist is not defined I'm also trying to come up with the best way to refresh the AJAX call every minute... but one thing at a time.
$(document).ready(function(){
function ajax_playlist(str1, callback){
$.ajax({
url: "http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType: 'jsonp',
success: function(data, status, xhr){
callback(data);
console.log(arguments);
}
});
}
ajax_playlist("str", function(pl) {
myPlaylist = [
{
mp3:'http://radio.gnradio.org:9966/vod/mp4:audio/file.m4a/playlist.m3u8',
artist:pl.data[0].track.artist,
title:pl.data[0].track.title,
cover:pl.data[0].track.imageurl
}
];
});
var description = 'Welcome to SilvertoneRadio.com BETA Online player. We will be gradually improving it.';
$('body').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description,
jPlayer:{
swfPath:'plugin/jquery-jplayer' //You need to override the default swf path any time the directory structure changes
}
});
});
myPlaylist is defined when the anonymous function passed to ajax_playlist is called.
That function is passed as the argument named callback.
That is called in the success function passed to the ajax method.
Asynchronous JavaScript and XML is asynchronous.
The success function won't be called until the HTTP response is received and processed.
So what happens is:
Ajax HTTP request is sent
description has a value assigned to it
ttwMusicPlayer is called (with myPlaylist which is currently undefined)
HTTP response is received
myPlaylist gets a value assigned to it
Move all the code that depends on myPlaylist having a value into your callback function.
AJAX is asynchronous, anything that depends on its result MUST be called in the success callback!
Move the ttwMusicPlayer call inside the function(pl) { ... } block (after the myPlaylist = [...];)
I am experiencing an issue in jQuery when I do multiple jsonp requests, all with the same jsonpCallback function. It seems that only for the one of those the callback function is triggered. Are JSONP requests somehow overwriting each other?
Below an example of doing 2 jsonp request to github, and even though both firebug shows that both of them return, the callback function getName is only called for one of them:
function getName(response){
alert(response.data.name);
}
function userinfo(username){
$.ajax({
url: "https://api.github.com/users/" + username,
jsonpCallback: 'getName',
dataType: "jsonp"
});
}
users = ["torvalds", "twitter", "jquery"]
for(var i = 0; i < users.length; i++){
userinfo(users[i]);
}
Your request fired only once because of how jsonp works.
Jsonp means adding a script tag to the page from an outside domain to get around Cross-Site Scripting protections built into modern browsers (and now IE6 and 7 as of April 2011). In order to have that script interact with the rest of the script on the page, the script being loaded in needs to call a function on the page. That function has to exist in the global namespace, meaning there can only be one function by that name. In other words, without JQuery a single jsonp request would look like this:
<script>
function loadJson(json) {
// Read the json
}
</script>
<script src="//outsidedomain.com/something.js"></script>
Where something.js would look like this:
loadJson({name:'Joe'})
something.js in this case has a hard-coded callback to load the JSON it carries, and the page has a hard-coded loadJson function waiting for scripts like this one to load and call it.
Now suppose you want to be able to load json from multiple sources and tell when each finishes, or even load JSON from the same source multiple times, and be able to tell when each call finishes - even if one call is delayed so long it completes after a later call. This hard-coded approach isn't going to work anymore, for 2 reasons:
Every load of something.js calls the same loadJson() callback - you have no way of knowing which request goes with which reply.
Caching - once you load something.js once, the browser isn't going to ask the server for it again - it's going to just bring it back in from the cache, ruining your plan.
You can resolve both of these by telling the server to wrap the JSON differently each time, and the simple way is to pass that information in a querystring parameter like ?callback=loadJson12345. It's as though your page looked like this:
<script>
function loadJson1(json) {
// Read the json
}
function loadJson2(json) {
// Read the json
}
</script>
<script src="//outsidedomain.com/something.js?callback=loadJson1"></script>
<script src="//outsidedomain.com/somethingelse.js?callback=loadJson2"></script>
With JQuery, this is all abstracted for you to look like a normal call to $.ajax, meaning you're expecting the success function to fire. In order to ensure the right success function fires for each jsonp load, JQuery creates a long random callback function name in the global namespace like JQuery1233432432432432, passes that as the callback parameter in the querystring, then waits for the script to load. If everything works properly the script that loads calls the callback function JQuery requested, which in turn fires the success handler from the $.ajax call.
Note that "works properly" requires that the server-side reads the ?callback querystring parameter and includes that in the response, like ?callback=joe -> joe({.... If it's a static file or the server doesn't play this way, you likely need to treat the file as cacheable - see below.
Caching
If you wanted your json to cache, you can get JQuery to do something closer to my first example by setting cache: true and setting the jsonpCallback property to a string that is hardcoded into the cacheable json file. For example this static json:
loadJoe({name:'Joe'})
Could be loaded and cached in JQuery like so:
$.ajax({
url: '//outsidedomain.com/loadjoe.js',
dataType: 'jsonp',
cache: true,
jsonpCallback: 'loadJoe',
success: function(json) { ... }
});
Use the success callback instead..
function userinfo(username){
$.ajax({
url: "https://api.github.com/users/" + username,
success: getName,
dataType: "jsonp"
});
}
$(function() {
function userinfo(username){
var XHR = $.ajax({
url: "https://api.github.com/users/" + username,
dataType: "jsonp"
}).done(function(data) {
console.log(data.data.name);
});
}
users = ["torvalds", "twitter", "jquery"];
for(var i = 0; i < users.length; i++){
userinfo(users[i]);
}
});
Not sure but the response I get from that call to the github API does not include gravatar_id.
This worked for me:
function getGravatar(response){
var link = response.data.avatar_url;
$('#list').append('<div><img src="' + link + '"></div>');
}
In jQuery, parsing a bunch of points to draw on a HTML5 canvas. Encountered a strange bug -- but my knowledge of this area is pretty limited so perhaps there's a good explanation.
This works every time:
var json = $.getJSON( "../models/" + id + ".json");
alert("fjkld");
paths = JSON.parse(json.responseText);
This fails every time:
var json = $.getJSON( "../models/" + id + ".json");
paths = JSON.parse(json.responseText);
Anyone have any idea why? Is it because the alert pauses something while the parser 'catches up'? That doesn't make intuitive sense to me but it's the only explanation.
Actually I know this is correct because if I hit "OK" on the alert really fast it fails again.
Can someone please explain to me why this is happening?
getJSON is asynchronous. This means that it returns immediately, before the XMLHTTPRequest has completed. Because alert is a blocking function, all code is halted until you press OK. If you take a while, the request has completed, so responseText is available; if alert isn't present, or you press OK very quickly, the HTTP request has not completed, so the text has not completed.
You need to use a callback function instead: this is a function that will be executed when the AJAX request is complete:
$.getJSON( "../models/" + id + ".json", function(paths) {
// access paths here
});
See the documentation for $.getJSON.
This happens because the getJSON call is asynchronous. Once the call to getJSON is complete all you know is that the browser has kicked off the request for the file. You do not know if the request has been completed or not. Sure, the call to the alert function gives the browser enough time (usually) to get the full file, but as you discovered sometimes that's not true.
Far better is to supply a callback that will be called once the file has been downloaded:
$.getJSON(fileName, function(data) {
paths = JSON.parse(data);
..do something with paths..
});
Although note that paths won't be available until the callback executes.
You need to set up a callback function in the getJSON call to ensure that the response has had time to complete. In the flow of the ajax call the function that generates the getJSON call continues while the getJSON happens. There is no guarantee that the json request has completed when teh JSON.parse() is being called. The proper syntax for the call is :
jQuery.getJSON( "../models/" + id + ".json", function(data, status, xhr){ JSON.parse(data);} )
Check out the api for the getJson call here: http://api.jquery.com/jQuery.getJSON/
Put your logic inside the callback.
$.getJson("../models/" + id + ".json", function(response) {
paths = JSON.pars(response.responseText);
});
Or something like that. As a request API call is an asynchronous call, you have to wait for the server response before you can move forward. That's where callbacks come in. They're called by the asynchronous API when the request is complete. They usually also have success status flags to tell you if your request was successful.
http://api.jquery.com/jQuery.getJSON/
I'm trying to return a list of select options to a JqGrid Add feature.
I have a javascript/jquery function that does a GET to get a string preformatted to work with JqGrid. I'm having trouble returning the results to the JqGrid though. How do I return the data from the jQuery Get function?
function getDealerPoolSelectOptions() {
var selectOptions = "1:A;";
$.get("DealerManagement/GetAllDealerPoolCodes", function(data) {
alert("Data: " + data.toString()); //Displays all the data I'm looking for
selectOptions = data;
});
alert("SelectOptions: " + selectOptions); //Just Displays the 1:A
return selectOptions;
}
$.get begins an asynchronous AJAX request and calls your callback function(data) ... once it is done. $.get itself returns before the request is complete. The alert("SelectOptions ...") part runs immediately (before the data is retrieved) so selectOptions isn't set yet.
jQuery ajax, by default, makes an asynchronous request (meaning it will make the request in the background, without blocking execution in the rest of the function).
EDIT: While you can make synchronous requests, I should note that this is very discouraged. Instead, you should design your code in a way that takes advantage of event driven programming.
You can make a synchronous request like this:
function getDealerPoolSelectOptions() {
var selectOptions = "1:A;";
$.ajax({
async: false,
url: "DealerManagement/GetAllDealerPoolCodes",
success: function(data) {
alert("Data: " + data.toString()); //Displays all the data I'm looking for
selectOptions = data;
}
});
alert("SelectOptions: " + selectOptions);
return selectOptions;
}
Probably you should describe your original problem. What you want to do with jqGrid?
Do you want to fill select of edit or search field with the data from the server? You should use dataUrl of the editoptions or the searchoptions. The feature (dataUrl) are introduced exactly for loading the data per ajax.
If the data which you can provide from the server can be only JSON and not in the format which are waiting by jqGrid you can use buildSelect additionally to reformat the data returned from the server. For more information see my old answer.
The alert gets called before the selectOptions = data; because ajax functions are called asynchronously. If you want something to happen, like adding the data to a grid, call it in the get callback after you set the selectOptions data.