How to get URL of Facebook Post made using Graph API? - javascript

I have been able to successfully post a status update with image to Facebook using the graph API via an AJAX call. Now I would like to get the URL of the post, and redirect the user to the post as soon as it has been made, but I can't figure out how to get the URL. I thought the URL would be included in the response success data object, but I have tried iterating through it, and all I got was seemingly random numbers. Does anyone know how I can get the URL of the post and send the user there? Thanks. Here is my code below:
$.ajax({
url:"https://graph.facebook.com/" + userID + "/photos?access_token=" + accessToken,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var obj = data[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
}
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});

Related

Jquery post and missing data

I'm retrieving an a list of sites, groups, and users. I'm concatenating and placing them in their respective variable, sending them in a query string to an aspx file.
var url = (Page._BASE_URL + 'Mo/Un/Unis/Unifie.aspx?' + getUserSecurityParameter() +
'&action=sending&userIds=' + encodeURI(userIds) +
'&siteName=' + encodeURI(site) +
'&groupName=' + encodeURI(groupName) +
'&siteList=' + encodeURI(siteList) +
'&team=' + encodeURI(team) +
'&users=' + encodeURI(users)+
'&site=' + encodeURI(site));
Ii'm using this code to retrieve those values on from the ajax post. I notice when I notice check the aspx source, There's so much data between the groups and sites that the users variable and data is never present.
var siteName = $.getUrlVar('siteName');
var groupName = $.getUrlVar('groupName');
var users= $.getUrlVar('users');
Is there a better way to do this so I won't have this issue? Because of missing users data it throws of a query that is written on the back end. Thanks in advance.
This is what I have now. When I try to send the data over I get an error. I can't see the what the error is unfortunately.
var requestParameters =
{
siteList: siteList,
team: team,
users: users,
siteName: site,
site: site,
group: group,
userId: userId,
securityCode: getUserSecurityParameter()
};
$.ajax({
url: Im._B + 'Mo/Uni/Unif/Ui.aspx/getValues',
type: "POST",
data: JSON.stringify(requestParameters),
contentType: "application/json; charset=UTF-8",
done: function (requestParameters, textStatus, jqXHR) {
var left = Math.floor((screen.width - 545) / 2);
windowManager.openFixed(url, 'DocumentListWindow', left, /* top: */ 10, /* width: */ 1480, /* height: */ 840);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error occurred trying to send the data.');
}
});
Ui.aspx.cs
[System.Web.Services.WebMethod]
public static string getValues(string requestParameters)
{
string mystuff = requestParameters;
return mystuff;
}
ERROR
"{\"Message\":\"Operation is not valid due to the current state of the object.\",\"StackTrace\":\"
Although there is technically no limit to the length of a query string, individual browsers do have limits. Follow Alex's advice and convert this to a post.

No 'Access-Control-Allow-Origin' header when receiving JSON data from server

I am trying to make the client side receiving JSON data from the Server, however, it constantly popped up the error method. When I try to use Chrome to debug, it popped up: XMLHttpRequest cannot load http://localhost:8080/TransportationNetwork/rest/paths?st=3,6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have tried to change dataType to 'jsonp', but it doesn't work. However, when I use POSTMAN to test the data from Server, everything works fine, I can see the JSON data comes from the server.
Here is the picture shows the testing result from POSTMAN:
Pictures shows POSTMAN testing result from server
The following is my code on both server side and client side:
Could anyone tell me how to add the 'Access-Control-Allow-Origin' header for my java code?(if it is this problem)
The Java Code:
#Path("/paths")
public class PathsResource {
PathDao pathDao;
public PathsResource() {
pathDao = new PathDao();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
//#Consumes("text/plain")
public List<DirectedEdge> pathsInfo(#QueryParam("st") String st) {
System.out.println("Searching paths : " + st);
return pathDao.getEdgeList(st);
}
}
The Javascript:
var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths";
$('#findPaths').click(function() {
getPaths();
});
function getPaths() {
console.log('display paths');
$.ajax({
type:'GET',
url: serviceURL,
dataType:'json', // data type get back from server
data:'st=' + dataToServer(), //data sent to server
success: renderList,
error: function(jqXHR, textStatus, errorThrown){
alert('Path Finder: ' + textStatus);
}
});
}
function dataToServer() {
var array = "";
str1 = $('#source').val();
str2 = $('#target').val();
array = str1 + "," + str2;
return array;
}
function renderList(data) {
//var parsedData = JSON.parse(data);
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#PathList li').remove();
$.each(list, function(index, path) {
$('#PathList').append('<li>'+ path.source + ' -> ' + path.target + ': ' + path.weight + '</li>');
});
}

Problems Reading json data return to jQuery

I have some json return data, I am unable to access any of the data within the JSON, I have used this method before and it works, but I can't seem to figure out what is going wrong here.
the data["json"] will print out the json data but data["default"] or data.default will not print out the individual information within the json data.
JSON: {"default":"y","mqdefault":"y","hqdefault":"y","sddefault":"y","maxresdefault":"y"}
the jquery is:
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
"default: " + data["default"] + "<br />mqdefault: " + data["mqdefault"] + "<br />hqdefault: " + data["hqdefault"] + "<br />JSON: " + data["json"]
);
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
Well i had run into a similar type of situation where i was getting a json data in the response from my server that i was able to print in log, but i was not able to access its variables.
Later i found out that this was because the data that was being received in the callback success function was not actually a json value. You might need to check if it is actually a json or else you can parse it to a json.
Possibly your data is not a proper json format due to which you are not able to access data["default"]

Returning JSON from an Ajax GET call - receiving an Undefined error on all but the first record in the JSON object

Here's my client side code:
$.ajax({
url: 'http://localhost/App.WebAPI/api/Messages/AppName',
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
function WriteResponse(messages) {
var strResult = "<table><th>AppId</th><th>Message</th>";
$.each(messages, function (index, message) {
strResult += "<tr><td>" + message.AppId + "</td><td> " + message.Message + "</td></tr>";
});
strResult += "</table>";
$("#divResult").html(strResult);
}
The URL in the Ajax call returns 3 records, but when they are output to the browser via "WriteResponse", here's what I get (blurred out to protect company information):
Is my .each method not formed correctly? I am not an expert in jQuery, so I wouldn't be surprised if I goofed up something simple. Notice that it does see all 3 records but it outputs "Undefined" in the 2nd and 3rd records... any ideas why??
The problem was that I had a foreign key relationship defined in my table (MSSQL) - I am using Entity Framework - and so when the JSON was returned by the WebAPI, the foreign key was included in the JSON, as expected, but for some reason it made the JSON look all funky. I removed all relationships in my table, ran the API call again, and now I am getting all my records back.
But I know that just works around the issue of having foreign keys, which I will investigate further.

Call a GET API each XX seconds, and put the JSON response in a CSV

I'm a newbie, and I apologize for this.
I am writing a script that will make a GET request. The result is a JSON array and the best deal would be to have it put automatically in a CSV/TXT file.
$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
station = JSON.parse(jimmi);
}             
var ar_len = jimmi.length
for (i=0; i < ar_len;) {
$("#results").html(
"Station: " + jimmi[i].name + "<br />")  
i++     
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
My problems:
* I get displayed only the last element of the array, and I can't figure out why.
* I would need to make this call automatically each 5 seconds
* The JSON results should be written into a CSV/TXT file.
Can someone help me?
BTW, the URL is https://its.navizon.com/api/v1/sites/1001/stations/ and you can log using demo#navizon.com - no password (read only)
Your problem is that you're changing the contents of #results for each element of jimmi by changing the entire inner HTML. So in the end, only the last element gets displayed. You need to use append instead. To make the call every 5 seconds, use the setTimeout method. Something this like:
function makeCall() {
$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
jimmi = JSON.parse(jimmi);
}
for (i=0; i < jimmi.length; i++) {
$("#results").append("Station: " + jimmi[i].name + "<br />");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
window.setTimeout(makeCall, 5000);
}
makeCall();
Note: The line station = JSON.parse(jimmi); is not useful because the variable station is never used. I changed it to something that made more sense.

Categories

Resources