I am trying to get buddypress avatars on a network’s main site from a sub-site. The way buddypress does avatars is really involved with loops and fallbacks etc and doesn’t consist of any database calls, which would have been straightforward.
Instead I thought maybe I will create a function on my main site to output the user’s avatar and then grab it with AJAX. But the cross-domain policy is in effect and I’m having difficulty understanding how to implement JSONP to get around it.
My javascript looks like this:
$('.external-avatar').each(function(){
var user_id = $(this).data('user_id');
$.ajax({
type: 'POST',
url: vars.rootAjaxurl,
data: {
action: 'bp_cross_site_avatar',
user_id: user_id,
},
success: function(data, textStatus, XMLHttpRequest, user_id){
$(".external-avatar.user-"+user_id).attr('src', data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
// alert(errorThrown);
}
});
});
Is there a way to get a request like this to work?
There’s two parts to this, the javascript ajax call needs specific variables included:
The important variables here for jsonp are
cache
,dataType
, andcrossDomain
. Note: when your dataType is jsonp it creates an additional varible ‘callback’. Also, by it’s very nature, jsonp istype
GET.The other important thing to note is in the
wp_ajax_nopriv_{action}
andwp_ajax_{action}
actions you need to include the callback and access-control header:I wrote a about using jsonp in WordPress if you want more details.
Pass the blog ID of the sub-site to your AJAX callback handler, use
switch_to_blog()
there and get the data you need.This way, you can stay on the same site with all front-end processing, while you get the information from the other site with PHP.