Posting to facebook wall using graph api - javascript

I'm trying to post a text with image to facebook wall using graph api.
I'm using following code snippet for this.
var body = {
message : 'this is a test message',
image : 'http://someurltoimage.png'
};
FB.api(
"/me/feed",
"POST",
{
"object": {
"message": body.message,
"picture": body.image
}
},
function (response) {
if (response && !response.error) {
//process when success
}
}
);
But I'm getting following error code.
error: Object
code: 100
error_subcode: 1349125
message: "Invalid parameter"
type: "FacebookApiException"
There's no document for this error.
Any advise will be appreciated.

"I'm trying to post a text with image to facebook wall using graph api."
You are using /feed, to upload a photo you have to use /photos call
You are sending an invalid parameter object which contains your parameters, to Facebook, the API doesn't know that your parameter Object is an object (I know, too many objects here, in another way, you're sending an object within an object
To solve all this, replace me/feed with me/photos and the 3rd argument (your object) with the body
var body = {
message : 'this is a test message',
url: 'http://someurltoimage.png'
};
FB.api("/me/photos",
"POST",
body,
function (response) {
if (response && !response.error) {
//process when success
}
}
);

Related

JSON Data Not showing from to view after retrieving using ajax

I retrieve Json data from controller using ajax. But I am trying to show the result in a specific div and tried so many things but couldn't figure it out what I am doing wrong. I can see in console that it is getting the json Data but it is just not showing in the specific div.
Here is the Json Data -
Object
postage_result:
costs:
cost:{item: "Parcel Post", cost: "15.80"}
delivery_time:"Delivered in 4 business days"
service:"Parcel Post"
total_cost:"15.80"
Ajax Code-
<script>
$.ajax({
url: '/ShoppingCart/GetFreight',
type: 'GET',
success: function (response) {
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
$.each(response.postage_result, function (i, val) {
$("#cost").append(document.createTextNode(val.total_cost));
})
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
View Code -
<td>Freight =<div id="cost"> </div></td>
Please suggest How should I do it to work .

how to handle ajax parsererror nicely?

I have a google ad project which requires me to get multiple "setTargeting('', '');" from an object array on json file (via url) --> {"country": "Netherlands", "city": "Amsterdam" }. So far everything works; however, suppose the network fails, or requested JSON parse failed, etc - I'd like to pass an empty array to make sure that the slot will still show ads with no targeting.
What would be a good practise for it?
Advertisements.cachedCategoriesByUrl = {};
Advertisements.getCategories = function(categoriesUrl) {
var cachedCategories = Advertisements.cachedCategoriesByUrl[categoriesUrl];
if(cachedCategories){
return cachedCategories;
} else {
var getCategories = $.ajax({
url: categoriesUrl,
data: { format: 'json' },
error: function(jqXHR, status, thrownError) {
=> I'd like to pass an empty array so the slot will show
ads with no targetting set.
However this doesn't seem to be working.
Do I need to do callback?
}
});
Advertisements.cachedCategoriesByUrl[categoriesUrl] = getCategories;
return getCategories;
}
}
Note:
return getCategories runs before the ajax call finishes. How do I make sure that return getCategories gets my error update(I want to pass an empty array if JSON request fails or invalid). Sorry I am in the learning process.
Solved it with this:
$.ajax({
url: ad.categoriesUrl
}).then(function(data){
Advertisements.advertisementSlot(ad, data);
}, function(data){
data = {};
Advertisements.advertisementSlot(ad, data);
});

How to post a custom post using facebook javascript api

Okay i have a website now with an input and button. When the user clicks a button, I want his input to be as a new feed on his facebook account.
I already have added the facebook javascript sdk and the graph api one
and I created a successful login button and a new feed button sending a standard text which "is this is a text feed".
So how can i post what the user inputs?
The code of posting is
function postshare() {
FB.api(
"/me/feed",
"POST",
{
"message": "this is a test post"
},
function (response) {
if (response && !response.error) {
/* handle the result */
document.getElementById('poststt').innerHTML = 'post shared succesfully';
}
}
);
If you have a text input on the page with an id, you can reference that input and get its value using document.getElementById. So if you had this input
<input type="text" id="fb_input" />
on your page, you could then do this:
function postshare() {
var message = document.getElementById("fb_input").value;
FB.api(
"/me/feed",
"POST",
{
"message": message
},
function (response) {
if (response && !response.error) {
/* handle the result */
document.getElementById('poststt').innerHTML = 'post shared succesfully';
}
}
);
}

FB ui feed get message after posting on wall

I'm using this function to initiate a UI feed to post on my wall a content from my website. :
FB.ui({
method: 'feed',
name: myname,
link: window.location.href,
picture: mypic,
caption: '',
description: desc
},function(response){}
});
I need to execute a callback inside the callback in which I can retrieve the message that the I inserted in the Facebook Dialog, I'm searching but not finding a way to get it, I also tried to delegate a keydown event to the dialog's textarea , but It does not work.
How can I solve this?
In order to extract data from the post that was created from the dialog you can retrieve the post_id from within the callback function that the dialog provides. Within the callback you'll be able to inspect the response object. It will contain the post_id provided that the post was successfully created.
With this post_id you can execute an additional call to the API and provide the post_id` as the endpoint:
https://graph.facebook.com/POST_ID
Or with the JavaScript SDK:
FB.api( '/POST_ID', function( response ) {
console.log( response );
} );
Take a look at the response object from the second call, it'll look something like this :
{
"id": "POST_ID",
"from": {
"name": "Lix",
"id": "XXXYYY"
},
"message": "Checkout this awesome link!",
"picture": "https://fbexternal-a.akamaihd.net/...",
...
}
As you can see, the message is contained in the response, so to enhance my previous example:
FB.api( '/POST_ID', function( response ) {
if ( response ){
console.log( response.message );
}
} );
And now we can put it all together with the FB.ui call:
FB.ui({
method: 'feed',
...
},function( response ){
if ( response && response.post_id ){
FB.api( '/' + response.post_id, function( response ) {
console.log( response );
} );
}
}
});

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources