get friends facebook mobile fb.ui hello world - facebook-graph-api

I am working on a facebook mobile web app. There is the following function.
function getUserFriends() {
FB.api('/me/friends&fields=name,picture', function(response) {
console.log('Got friends: ', response);
if (!response.error) {
var markup = '';
var friends = response.data;
for (var i=0; i < friends.length && i < 25; i++) {
var friend = friends[i];
markup += '<img src="' + friend.picture + '"> ' + friend.name + '<br>' + friend.id + '<br>';
}
document.getElementById('user-friends').innerHTML = markup;
}
});
}
When it returns the pictures are missing.
The console log returns:
[06:02:12.503] GET http://m.mochirestaurant.com/fb/%5Bobject%20Object%5D [HTTP/1.1 404 Not Found 77ms]
While it should return something like:
http://profile.ak.fbcdn.net/hprofile-ak-ash2/276211_285403872_5043326_q.jpg
I think I misconfigured something in my facebook app but don't know what it is

[06:02:12.503] GET http;//m.mochirestaurant.com/fb/%5Bobject%20Object%5D [HTTP/1.1 404 Not Found 77ms]
Instead of a real value you can see that it says [object] in there (with the brackets URL-encoded) – which is what browsers return when you are trying to bring an object into a string context. (And because that is not a full URL beginning with http://…, your browser treats it as a relative address and tries to request it from your domain.)
So obviously friend.picture at this point in your code is not a string value, but an object.
(So far for the debugging and spotting-the-error-part.)
This stems from the October 3, 2012 Breaking change regarding the user/picure connection,
/picture connection will return a dictionary when a callback is specified
We will start returning a dictionary containing the fields url, height, width, and is_silhouette when accessing the /picture connection for an object and specifying a callback property. Currently we just return the picture URL as a string.
So you have to use friend.picture.url in your code to get the actual string property containing the user picture’s URL.

Related

Update SharedWith using Sharepoint 2013 API

I am trying to update specific property of Sharepoint 2013 list item, ie. 'SharedWithUsersId'. Although I get the response code as 204 (indicating success), when I check the list item again, I am not seeing any change in the sharedWithUSersId. When I tried changing other properties, like title, it worked like a charm. So, I want to know if 'sharedWithUSersId' property cannot be edited via this particular api call?
Cheers, Z
It can be changed, but not directly. You can do it by REST API. For example:
function setNewPermissionsForGroup() {
var endpointUri = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getbytitle('";
endpointUri += listTitle + "')/roleassignments/addroleassignment(principalid=" + groupId;
endpointUri += ",roledefid=" + targetRoleDefinitionId + ")?#target='" + hostweburl + "'";
executor.executeAsync({
url: endpointUri,
method: 'POST',
headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },
success: successHandler,
error: errorHandler
});
}
You can find more details here

Invalid argument for appscript UrlFetchApp.fetch

I'm trying to fetch data from the facebook FQL api using google appscript. Unfortunately, I keep getting the following error:
Error encountered: Invalid argument: https://graph.facebook.com/fql?q=SELECT+post_id,share_info,comment_info,like_info,created_time+FROM+stream+WHERE+post_id+IN+(SELECT+post_id+FROM+stream+WHERE+source_id='SOME_SOURCE_ID'+AND+created_time+>+1369869370+AND+created_time+<+1377645370+ORDER+BY+created_time+DESC+LIMIT+0,100)&access_token=XXXXXXXXX
If I copy/paste the url into my browser, I get a valid JSON response which makes me think that the url is valid, however, if I look at the execution transcript, it points me to the var postfetch = UrlFetchApp.fetch(...) line.
Here's my code.
var posturl = "https://graph.facebook.com/fql?q=SELECT+post_id,share_info,comment_info,like_info,created_time+FROM+stream+WHERE+post_id+IN+" +
"(SELECT+post_id+FROM+stream+WHERE+source_id='" + source + "'+AND+created_time+>+" + istartEpoch.toString() +
"+AND+created_time+<+" + iendEpoch.toString() + "+ORDER+BY+created_time+DESC+LIMIT+0,100)&access_token=" + token;
var postfetch = UrlFetchApp.fetch(posturl);
var postjson = postfetch.getContentText();
var postdata = Utilities.jsonParse(postjson);
It turns out that < and > aren't valid characters to put into a url. Changing them to %3E and %3C and now all is right with the world.

Jquery Autocomplete x Amazon CloudSearch encoding

Im using Amazon CloudSearch as source to a JQuery Autocomplete select. It works very well, but for a reason that I`m not able to identify, when only one result is returned the encoding becomes a mess.
The solution works as follows:
Text input where people type neighborhoods or streets of a given city:
<div id="searchFormContainer">
<input type="text" value=" Digite o bairro ou rua" name="inputSearch" id="inputSearch"/>
</div>
JQuery autocomplete config:
var sourceFunction = function (request, response) {
var successFunction = function (places) {
var placesWithLabel = jQuery.map(places, function (place) {
var label = (place.addressName) ? place.addressName+', ' : '';
label += place.neighborhoodName;
var value = label;
return {label:label, value:value};
});
if(placesWithLabel.length==0){
placesWithLabel.push({label:"Não encontrado", value:""})
}
response(placesWithLabel);
}
var ajaxOptions = {appendTo: '#searchFormContainer',
url: '/textSearch', dataType: "json",
data: {strToSearch: request.term,
cityName: self.place.city.name},
success: successFunction};
jQuery.ajax(ajaxOptions);
};
var openFunction = function () {
jQuery(this).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
};
var closeFunction = function () {
jQuery( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
};
var selectFunction = function (event, data) {
if(data.item.value==""){
return;
}else{
//redirect to result page
}
};
**var autocompleteOptions = {appendTo: '#searchFormContainer',
source: sourceFunction,
minLength: 1,
open: openFunction,
close: closeFunction,
select: selectFunction};**
**$('#searchFormContainer #inputSearch').autocomplete(autocompleteOptions);**
It works successfully, calling my python view named textSearch, which does:
def textSearch(request):
results = simplejson.loads(requests.get('http://%s/2011-02-01/search?' % (settings.SEARCH_CLOUD_HOST), params=fieldsParameter).text)['hits']
return HttpResponse(simplejson.dumps(results), mimetype='application/json')
Taking for example a search for the street named Oscar Freire in neighbourhood Cerqueira César, when I type Oscar Fr in the autocomplete, Amazon CloudSearch returns me two results:
[16/Apr/2013 23:59:47] "GET /textSearch?strToSearch=Oscar+F&cityName=S%C3%A3o+Paulo HTTP/1.1" 200 682
Neighbourhood from Amazon --> Cerqueira César
Returns from Amazon --> {'id_address': u'52267', 'neighborhoodName': u'Cerqueira C\xe9sar', 'addressName': u'Rua Oscar Freire', 'id_neighborhood': u'19694'}
Neighbourhood from Amazon --> Jardim Anália Franco
Returns from Amazon --> {'id_address': u'61073', 'neighborhoodName': u'Jardim An\xe1lia Franco', 'addressName': u'Rua Jos\xe9 Oscar Abreu Sampaio', 'id_neighborhood': u'19881'}
But, typing one more letter with the search keyword Oscar Fre, which returns only one result I`ve:
[16/Apr/2013 23:59:49] "GET /textSearch?strToSearch=Oscar+Fr&cityName=S%C3%A3o+Paulo HTTP/1.1" 200 286
Neighbourhood from Amazon --> Cerqueira CĂŠsar
Returns from Amazon --> {'id_address': u'52267', 'neighborhoodName': u'Cerqueira C\u0102\u0160sar', 'addressName': u'Rua Oscar Freire', 'id_neighborhood': u'19694'}
As we can see in the output, the returned object is the same (id_address is the same for both results). The amazon object (RAW JSON extracted from CloudSearch) for this entry is:
{"rank":"-text_relevance","match-expr":"(label 'Oscar Freire')","hits":{"found":1,"start":0,"hit":[{"id":"52267","data":{"address":["Rua Oscar Freire"],"bairro":["Cerqueira César"],"fieldtype":["address"],"id_address":["52267"],"id_neighborhood":["19694"],"latitude":["-23.568315"],"longitude":["-46.66293"],"text_relevance":["310"]}}]},"info":{"rid":"e2467862eecf73","time-ms":3,"cpu-time-ms":0}}
For me is clear the fact that the response is coming with wrong encoding to my python view.. But I can`t realize where this problem begins. If it is a bad behaviour from JQuery autocomplete or a problem with Amazon response. Any ideas?
Best Regards
I think it's important to isolate the possible causes of the issue. There are too many possible sources of encoding problems here, you should start with removing possible sources of problems.
If you search for "Oscar Fr" vs. "Oscar F" in a browser (using the CloudSearch search endpoint), does the encoding change at all? If it stays the same, then the problem is not CloudSearch, and you can move up the stack.

Django - jquery : populate combobox based on selection of another combobox

I am quite new to Django and jquery stuff. I am trying to populate a comboBox (ChoiceField in Django) based ont the choice selected in another comboBox (without reloading the page).
I can't find any simple example of such a basic application of ajax.
For now I'm call the following ajax function when I select an item from the first dropdown list.
function get_asset_from_type(){
var type_asset = $("#id_type").val();
var data = {type_asset:type_asset};
var args = {type:"POST", url:"/asset/etatType/", data:data};
$.ajax(args);
alert(type_asset);
return false;
};
It alerts the right type but gives a 403 error on the given url. Weird thing is this url works the first time I load the page. I don't understand what's going on..
EDIT:
403 error seems to be gone, remains the initial question :)
I think you're running up against a CSRF problem. As Django by default blocks POST requests that do not have a CSRF Token with a 403. There are a couple ways to deal with this in JS. One is to pull the value out of the cookie, the code to do that can be found here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
or you can do it by passing the CSRF_TOKEN in with the javascript script tag:
<script src='myjavascript.js?CSRF_TOKEN={{ csrf_token }}'></script>
Note that it's using a double braket, instead of {%%}. This gets the value of the token, instead of the form input.
function getOptionsFromScriptSrc() {
// Get last script tag in parsed DOM.
// Due to the way html pages are parsed,
// the last one is always the one being loaded.
var options = {}
var js_src = $('script').last().attr('src');
if(js_src.match(/\?/)) {
var options_list = js_src.split('?')[1].split('&');
for(var i = 0; i < options_list.length; i++) {
var tmp = options_list[i].split('=');
options[$.trim(tmp[0])] = $.trim(tmp[1]);
}
}
return options;
}
function get_asset_from_type(){
var options = getOptionsFromScriptSrc();
var type_asset = $("#id_type").val();
var data = {type_asset: type_asset, csrfmiddlewaretoken: options['CSRF_TOKEN']};
var args = {type:"POST", url:"/asset/etatType/", data:data};
$.ajax(args);
alert(type_asset);
return false;
};
I haven't, of course, tested this code, but I have used this method before and it works pretty well.
To the main problem of populating a select box, you need to specify a callback for your ajax post, and then deal with the data returned from your server:
function get_asset_from_type(){
var options = getOptionsFromScriptSrc();
var type_asset = $("#id_type").val();
var post_data = {type_asset: type_asset, csrfmiddlewaretoken: options['CSRF_TOKEN']};
$.post('/asset/etatType/', post_data, function(data){
// Assuming server is going to respond with the html of the options, eg: <option value="1">One</option><option value="2">Two</option>...
$('#id_ofmyselectbox').append(data);
});
};

Redirect Entry form in SharePoint back to itself once entry submitted?

The issue I have is that people in my group are using a link to an Entry Form to post new itmes to a SharePoint list. Everytime they click 'submit' to post new item, SharPoint redirects them to the list.
I need a solution for SharePoint to direct them to the empty Entry form instead, no matter how many times they need to use it.
Is there such solution? Thanks,
I already have this "/EntryForm.aspx?Source=http://" in the link to the Entry form, but works only 2 times, after that will direct to the list.
Essentially you need to ensure that the Source parameter is always set to EntryForm.aspx so that no matter how often you loop through the form you always get redirected back to a new one at the end. You knew this, but I am just clarifying!
Simplest method would be some javascript to test this source parameter and if its not what you want then redirect the request so it is.
If you can edit the EntryForm.aspx page in SharePoint Designer then add this javascript to the page somewhere:
<script type="text/javascript">
if (gup("ok") != 1) {
if (gup("source") != window.location.href) {
window.location = window.location.href + "?&source=" + window.location.href + "&ok=1";
}
}
function gup( name ){
//This function returns the URL parameter specified
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
Essentially this is just redirecting your requests to this page so the source is always itself. The ok parameter is just to ensure that it only does it once.
This is not perfect code, but it demonstrates the idea (and it works!)
gup (Get URL Parameter) function is taken from here and I find it really useful.
Hope it helps
Charlie