Trouble building FB.api query - javascript

OK so I'm working on a Facebook Group Feed that loads more results, but I'm having trouble building the initial query for it all to work.
In the first if statement below, you can see where I put the parts of the query into variables and then call the function, passing those variables. This all works fine...
if (response.status === 'connected') {
// Logged into your app and Facebook.
console.log('Welcome! Fetching your information.... ');
var path = '/',
method = 'POST',
params = {
batch: [
{method : 'GET', name : 'user', relative_url : '/me?fields=id,name,picture'},
{method: 'GET', name : 'post-ids', relative_url: '/group-id/feed?fields=fields{with field expansion}',omit_response_on_success : false}
]
};
loadFeed(path, method, params);
}
The funciton below is where I'm having trouble. The first time the function is called, I need to put those three variables together into one, and call it with FB.api. You can see the function here:
function loadFeed(path, method, params) {
console.log('------------------');
console.log(path + ', ' + method + ', ' + params);
if(path != 'undefined') {
if(method != 'undefined') {
if(params != 'undefined') { var query = '{\'' + path + '\', \'' + method + '\', ' + params + '}'; }
}
else { var query = path; }
}
$('#load-more').css('display', 'hidden');
FB.api(query, function (response) {
console.log(response);
// first time page loads, response[0] is the login, and response[1] is the feed
// each time after that, response[0] is the feed
if(response.length > 1) {
var membody = JSON.parse(response[0].body),
feed = JSON.parse(response[1].body);
} else {
var feed = JSON.parse(response);
}
if(feed.paging) {
if(feed.paging.next) {
var load_more = '<div id="load-more"><center>Load more</center></div>',
method = '',
params = '';
$('#feed').append(load_more);
$('#load-more').click( function() {
loadFeed(feed.paging.next);
});
}
}
});
}
On the first call of this function, I get this error:
error: Object
code: 2500
message: "Unknown path components: /', 'POST', [object Object]}"
type: "OAuthException"
This seems to tell me that I've basically put the query together wrong, but I've tried a few different things and none of it is working. You can see in the error message that there's a missing single quote at the beginning of the query, and I've not been able to figure out how to keep the single quote there.
Does anyone have any ideas on how I can fix this problem?
Also, if you know a better way to do all this then I'd appreciate that as well!

It seems you are building your Javascript API call with HTTP API parameters.
To query JS API for user:
FB.api(
"/me", // or "/99999999999" the user's id
function(response) {
if (response && !response.error) {
/* handle the result */
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
To query JS API for group:
FB.api(
"/{group-id}",
function(response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/group

Related

API Jive get categories error : Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/

i use Jive and i want to get all categories and for each category, i want to create a checkbox for each of them.
Currently, i have my array with all categories, but when i try to create checkbox, it return me this error :
" Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/ "
Someone can help me ?
///////////////// function checkbox for each category ////////////////
$("#submit_a_question").click(function(e) {
e.preventDefault();
$("#modal").addClass('is-show');
$("#ideasContainer").height((height + 100) + "px");
resizeIframe();
fieldsPlaceholder(appLang);
var categoriesToShow = categories(placeID);
var container = $('#listCheckboxCategories');
var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = $('input />', {type: 'checkbox'});
if(tileConfig.isThereFilterRadios == "Yes"){
$('#ShowCategories').show();
$('#listDropdownCategories').show();
$.each(categoriesToShow.res, function(index, value) {
CheckboxCreate.appendTo(container);
});
}
///////// function to get all categories in an array /////////
function categories(placeID){
var request = osapi.jive.corev3.places.get({
uri : '/api/core/v3/places/' + placeID
});
// var res = [];
request.execute(function(response) {
if (typeof response.error != 'undefined') {
console.log("API call failed");
} else {
console.log(response);
response.getCategories().execute(
function (res){
console.log("cat",res);
});
}
});
}
I was able to execute the call successfully by using "/places/{placeId}" in the URI as below:
osapi.jive.corev3.places.get({uri: '/places/1003'}).execute(function(response) {
console.log(response);
});
For which I have received the place object in the response, as expected:
{ type: "space",
parent: "http://localhost:8080/api/core/v3/places/1000",
placeTopics: Array(0),
displayName: "water-cooler",
iconCss: "jive-icon-space", …}
Are you sure your "placeId" has the correct value? Maybe log the URI you are sending before making the call and check if the format matches the one I have mentioned above. Thanks.

YQL AJAX cross domain request stopped working

I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any data?

Local storage key verification fails in firefox

I'm trying to generate html content based on the presence of a specific key in the local storage. The code is as follows:
// Check if the user is signed in or not
if(localStorage.getItem("token") === null) {
document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
} else {
document.getElementById("main").innerHTML = document.getElementById("profileview").innerHTML;
}
The profile view is always shown even though there is no token key set in the local storage:
localStorage
Storage { token: "undefined", length: 1 }
Why?
Edit:
The token is being set with the response value of an AJAX request:
function sign_in() {
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/sign_in";
method = "POST";
formId = "#signin_form_id";
$form = $(formId);
form_data = get_form_data($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: form_data
};
// Make the request
$.ajax(request).done(function(data) { // Handle the response
// Attributes are retrieved as object.attribute_name
// alert(obj.count);
if(data.successSignIn === false) {
// Login failed we show the welcome page
alert(data.message);
document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
} else {
// Login succeeded. We load the user's info, his messages and also a form in which he can type messages
// Save the token received from the server. Could also be stored as a cookie
localStorage.setItem('token', data.token);
// Go to the home page
go_home();
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
);
location.reload();
}
Edited: Try this for set item localStorage.setItem("token", typeof undefined === data.token ? undefined : data.token). It is avoided to be string "undefined".
I suggest that:
1) Replace to if(localStorage.getItem("token")) {...}
3) Also, you can do your example through ternary operator
var welcomeText = document.getElementById("welcomeview").innerHTML,
profileText = document.getElementById("profileview").innerHTML;
document.getElementById("main").innerHTML = (localStorage.getItem("token")) ? welcomeText : profileText
You'd never enter the if section as "undefined" === null is always false.
You'd want to check for if(localStorage.getItem("token") === "undefined") in your case.

Sending Query String and Session information using Ajax

I am using Ajax to create comments and its not working , and i am not sure where the problem is. I am thinking it might be in the way i am reading UserID and VideoID
I have UserID saved in a session, and the videoID is saved in Query String.
am i reading them wrong?! if yes how can i read them?
here is my js code:
<script type="text/javascript">
$(document).ready(function () {
$('#btnPost').click(function (e) {
$.ajax({
url: "Ajax/ProcessAddComment.aspx",
data: {
commenttext: $('.txtcomment').val(),
videoid: Request.QueryString["d"],
userid: $.session.get('UserID')
},
success: function (data) {
alert(data);
},
error: function () {
}
});
});
$.ajax({
url: "Ajax/ProcessFindComment.aspx",
data: { videoid: Request.QueryString["id"] },
success: function (data) {
// Append to the bottom
// of list while prepend
// to the top of list
$('.postlist').html(data);
},
error: function () {
alert('Error');
}
});
});
I assume you're using this plugin to get and set your session.
I think your problem is: Request.QueryString
Try using the following JS function to get a value from the querystring rather than that:
function (key) {
if (!key) return '';
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return (match && decodeURIComponent(match[1].replace(/\+/g, " "))) || '';
};
Note: you can use the network tab in your developer window (F12 in most browsers) to see the Ajax data. The error console in there should tell you if there's a JavaScript error, and the network tab should tell you what was in the Ajax request and response.

Retrieve data from ajax query

So I've got a website where I want to click a button, check to see if the user has certain permissions, and if so popup a window to a new web page. On the java script I've got something like this:
function sendAjax(methodName, dataArray, success, error, category) {
var error2 = error || function () { };
$.ajax({
type: 'POST',
url: '/PermissionChecker' + methodName,
data: JSON.stringify(dataArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (r, s, x) { if (!success || success(r, s, x) != false) if (typeof (window.ChangeLogAdd) == 'function') { ChangeLogAdd(category); } },
error: error2
});
}
function CheckPermissions() {
sendAjax("CheckPermission", null, function (data) { var permission = eval('(' + data + ')'); if (permission == true) { alert('yay'); } else { alert('nay'); } }, null, 'Check Permission');
}
And the C# side is a simple function that does an if check and returns a bool. The function call goes through fine, but when it returns the bool I get a javascript error "Expected ']'". I assume this has something to do with my success function:
function (data) {
var permission = eval('(' + data + ')');
if (permission == true) {
alert('yay');
}
else {
alert('nay');
}
}
seeing as I didn't get this error before I tried what I'm doing there, so I was wondering how I would go about getting the data back from the ajax call to make pass the permission == true if/else check
Don't use eval for this purpose. It's unsafe and the source of many bugs. Just make the server respond with JSON and use $.getJSON.

Categories

Resources