Facebook batch calls with JSONP - facebook

As of 10.04.2012,
There is a short paragraph in the Facebook developer document for 'batch request' entitled: Batch calls with JSONP, which reads:
"The Batch API supports JSONP, just like the rest of the Graph API -
the JSONP callback function is specified using the 'callback' query string
or form post parameter."
I thought that meant you can also do a batch request using JSONP from Javascript (which will be a GET request, as JSONP works only as a GET request), so I tried that, with adding a 'batch' parameter (containing objects describing requests for batch as in the doc) to the query string. Response from FB server was:
Only POST is allowed for batch requests
So, questions:
1. What did they mean in that paragraph?
2. Is there a way to do an asynchronous batch request from Javascript?

I get the same. Sample code is
jQuery.support.cors = true;
var AjaxRequest = jQuery.ajax( {
url: "http://graph.facebook.com/",
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: { "access_token": AccessToken, "batch": BatchRequest },
dataType: "jsonp",
error: function( jqXHR, textStatus, errorThrown ) {
... show error stuff
},
success: function( Return, textStatus, jqXHR ) {
showLog( "Return " + JSON.stringify( Return ) );
showLog( "textStatus " + textStatus );
showLog( "jqXHR " + JSON.stringify( jqXHR ) );
if ( Return.error ) {
... go away
}
else {
... use the data
}
}
} ); // eo ajax request
which gives
Return {"error":3,"error_description":"Only POST is allowed for batch requests"}
textStatus success
jqXHR {"readyState":4,"status":200,"statusText":"success"}
i.e. it successfully sends back an error message. JSONP translates the POST type to a GET, which Facebook doesn't support...
To answer qu.2 you can use FB.api to do asynchronous batch request in javascript. I was trying out JSONP because IE8 keeps hanging on the return from Facebook with FB.api.

Related

How i can perform a POST request using fireFox RESTClient add-in

I have this function to perform a POST request to a SharePoint Online site collection:-
function SetListColumnReadOnly() {
$.ajax
({
// _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
// You can replace this with other site URL where you want to apply the function
url: "https://****.sharepoint.com/_api/web/lists/getByTitle('tickets')/fields/getbytitle('defineFields')",
method: "POST",
data: JSON.stringify({
'__metadata': {
// Type that you are modifying.
'type': 'SP.FieldText'
},
'ReadOnlyField': true
}),
headers:
{
// IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.
// "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
"IF-MATCH": "*",
"X-HTTP-Method": "PATCH",
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
//"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data, status, xhr) {
console.log("Success");
},
error: function (xhr, status, error) {
console.log("Failed");
}
});}
Now how we can run this POST inside the FireFox's RESTClient addin or anyother tool using the browser credentials?
when i tried this >> i got forbidden error:-
Also with those headers:-

Retrieving params with sinatra on form submit. Params is undefined

I am having trouble accessing params in Sinatra after submitting a form. This is my form:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
//grab the inputs from address_section
//data: $('.add_address_section .add_address_field').map(function() { return $(this).val() }),
data: [1,2,3],
dataType: "json",
success: function(data) {
debugger;
}
});
}
And this is my endpoint:
require 'sinatra'
require 'jobcoin_client'
get '/' do
erb :add_coins
end
post '/mix_addresses' do
puts params
end
I'm getting to the endpoint, but the params are blank. Shouldn't it be [1,2,3]? Instead, it's:
{"undefined"=>""}
Anyone see what I'm doing wrong?
Several issues here :)
Sinatra configuration
Main problem is coming from the fact that Sinatra doesn't deal with JSON payloads by default. If you want to send a JSON payload, then the easiest solution will be :
To add rack-contrib to your Gemfile,
Then, require it in your sinatra app: require rack/contrib
And load the middleware that deals with this issue: use Rack::PostBodyContentTypeParser
And you should be good to go!
Source: several SO post reference this issue, here, here or here for instance.
jQuery ajax call
Also, note that there might be some issues with your request :
You'll need to use a key: value format for your JSON payload: { values: [1,2,3] }
You'll need to stringify your JSON payload before sending it: data: JSON.stringify( ... )
You'll need to set the request content type to application/json (dataType is related to the data returned by the server, and doesn't say anything about your request format, see jQuery ajax documentation for more details).
Eventually, you should end up with something like this on the client side:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ values: [1,2,3] }),
success: function(data) {
debugger;
}
});
}

How to make Yammer REST API Call to get authenticated user's profile information?

I am trying to call Yammer REST API for getting authenticated user's information using the following code:
$(document).ready(function() {
$.ajax({
method: "GET",
url: "https://www.yammer.com/api/v1/users/current.json",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(data) {
if (data.Success) {
alert(data);
}
},
error: function(xhr2, status2) {
alert(xhr2.status);
}
});
});
However, it is always going to error method. Can anyone guide me to proceed on this piece?
You're not sending the API any authentication information, so how does it know what user it's supposed to be pulling down? You should take a look at the Javascript SDK.
I had the same problem. Change url from "https://www.yammer.com/api/v1/users/current.json" to "users/current.json" solves the issue (it will be going to success method)

Promise response works with GET, but not with POST in XHR

I am trying to call a URL through XHR.post on the DOJO 1.8. I need catch the STATUS property and getHeader() from promise response, but the problem is, when I call my URL with POST I don't have any promise, and when I call with GET I have all properties that I need, but I only can send the request as POST.
The most strange is that I have another code in AngularJS which works well, this code does the same thing. I am testing DOJO and AngularJS.
I need catch the STATUS information to check if it is 201(created), if true I need catch getHeader('location') and call the URL that I picked up from getHeader('location').
Look at my method in Dojo 1.8:
checkCreation: function(typeFile, id){
var promise = xhr('/rest/list/one', {
handleAs: 'json',
method: 'post',
accepts: 'application/json',
headers: {
Accept: 'application/json',
id: id,
type: typeFile
}
});
promise.response.then(function(response) {
console.log("status", response.status);
console.log("options", response.options);
console.log("url", response.url);
console.log("timestamp", response.options.timestamp);
console.log(response);
});
},
I discovered the problem, I commented the lines followings and now works fine.
//handleAs: 'json',
//accepts: 'application/json',
The handleAs you need to use only when you have a JSON response. About "accepts" I haven't found what difference between "accept" and "Accept"(inside headers) yet.
Now I can take my informations:
console.log('location: ', response.getHeader('location'));
console.log("status: ", response.status);

what is the use beforeSend function in (Jquery) Ajax

What is the use of beforeSend Function in jQuery Ajax?
How to use the jQuery function?
I am Using jQuery 1.6.0, and Using Jersey API (Restful Web services) on Server Side.
$.ajax({
type: "GET",
url:ajax_url,
dataType: "json",
contentType: "application/json",
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic "+ btoa(username + ':' + password));
},
success:function(data){
alert(data.groups);
},
error:function(xhr,err){
console.log("readyState:"+xhr.readyState+"\nstatus: "+xhr.status)
alert(xhr.responseText)
alert("Service is not Available , Try it after Some time");
}
});
Java Code :
#GET
#Produces(MediaType.APPLICATION_JSON)
public String authCheck(){
return "({"groups": "success"})";
}
Whenever I am sending for authentication I am getting success response.
How to use beforeSend function and does we need to do any thing on server side?
Generally beforeSend() is used to do some stuff before actually send AJAX request like set Custom header and etc...
but your need is different that you want to authenticate user before your ajax call than
create one another function which give you User is authenticated or Not in Response
suppose this function is checkAuth();
so use
type: "GET",
url:ajax_url,
dataType: "json",
contentType: "application/json",
async: false,
beforeSend:checkAuth,
.
.
.