in facebook fql theres this code
https://developers.facebook.com/docs/reference/api/batch/
curl \
-F 'access_token=…' \
-F 'batch=[ \
{"method": "GET", "relative_url": "me"}, \
{"method": "GET", "relative_url": "me/friends?limit=50"} \
]'\
https://graph.facebook.com
it suppose to to be sent with json
but I really dont understand how to do this
any help ?
thanks
You can simple use the BatchFB api its very powerful and easy , you dont have to deal will all of these stuff and it use the fql
for example to get all your friends
Later<ArrayNode> friendsArrayList = this.Batcher.query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
for (JsonNode friend : friendsArrayList.get()) {
.......
}
and its batched
I believe your question is how to execute a batch request using Facebook Graph API. For this you have to issue a POST request to
"https://graph.facebook.com"
and the post data to be sent should be
"batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#accesstoken"
in your case [#accesstoken must be replaced with your access token value].
This request will return the details of the owner of the access token(normally the current logged in user) and a list of 50 facebook friends(contains id and name fields) of the user along with page headers(can be omitted).
I am not sure whether you meant java or Javascript. Please be specific on it.
I am a C# programmer basically. Will provide you a code to execute the above request in C# here.
WebRequest webRequest = WebRequest.Create("https://graph.facebook.com");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-UrlEncoded";
byte[] buffer = Encoding.UTF8.GetBytes("batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#ACCESSTOKEN");
webRequest.ContentLength = buffer.Length;
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse != null)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string data = streamReader.ReadToEnd();
}
}
}
}
Here the variable data will contain the result.
Salah, here is the example i use as reference, i am sorry though i do not remember where i found.
FB.api("/", "POST", {
access_token:"MY_APPLICATION_ACCESS_TOKEN",
batch:[
{
"method":"GET",
"name":"get-photos",
"omit_response_on_success": true,
"relative_url":"MY_ALBUM_ID/photos"
},
{
"method": "GET",
"depends_on":"get-photos",
"relative_url":"{result=get-photos:$.data[0].id}/likes"
}
]
}, function(response) {
if (!response || response.error) {
console.log(response.error_description);
} else {
/* Iterate through each Response */
for(var i=0,l=response.length; i<l; i++) {
/* If we have set 'omit_response_on_success' to true in the Request, the Response value will be null, so continue to the next iteration */
if(response[i] === null) continue;
/* Else we are expecting a Response Body Object in JSON, so decode this */
var responseBody = JSON.parse(response[i].body);
/* If the Response Body includes an Error Object, handle the Error */
if(responseBody.error) {
// do something useful here
console.log(responseBody.error.message);
}
/* Else handle the data Object */
else {
// do something useful here
console.log(responseBody.data);
}
}
}
});
Related
I am stuck in very common error JSON parse error cannot figure out web service is faulty or fetch code I get a response from this web service when I test it in my postman it return two objects but when I want to login from this web service it always gives parse error
React Native Function to loginUser where may be error is present
UserLoginFunction = () =>{
const { UserContact } = this.state ;
const { UserPassword } = this.state ;
if(this.state.UserContact == ""){
ToastAndroid.show('Pleas Enter Contact Number Correctly ',ToastAndroid.SHORT)
}
else if (this.state.UserPassword == ""){
ToastAndroid.show('Please Enter Password Correctly',ToastAndroid.SHORT)
}
else{
fetch(urls.localhosturl + urls.login, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_contact: UserContact,
user_password: UserPassword,
//user_name: UserName,
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
//Save User Details to Local Storage
AsyncStorage.setItem("userContact", JSON.stringify(UserContact));
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('Home',{user_contact:UserContact,});
}
else{
ToastAndroid.show(responseJson,ToastAndroid.SHORT);
//Alert.alert(string,responseJson);
}
}).catch((error) => {
console.error(error);
});
}
}
PHP webservice
<!-- begin snippet: js hide: false console: true babel: false -->
<?php
// Importing DBConfig.php file.
include 'config.php';
// Creating connection.
$con = mysqli_connect($host_name, $host_user, $host_password, $database_name);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json, true);
$user_contact = $obj['user_contact'];
$user_password = $obj['user_password'];
// $user_contact = $_REQUEST['user_contact'];
// $user_password = $_REQUEST['user_password'];
//$user_name = $obj['user_name'];
$Sql_Query = "select * from user_information where user_contact = '$user_contact' and user_password = '$user_password' ";
$check = mysqli_fetch_array(mysqli_query($con, $Sql_Query));
if (isset($check)) {
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson;
} else {
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again';
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon;
}
$result = $con->query($Sql_Query);
$array = $result->fetch_assoc();
$json = json_encode($array, true);
echo $json;
mysqli_close($con);
It looks like the standard output of your PHP service is used as the source of the JSON.
In that case, the fact that you are spitting out the following line is causing you trouble:
echo $SuccessLoginJson;
You may want to either suppress this message, write it to a log file, or perhaps write it to standard error instead. In any case, you've turned your web service into something that gives your client two results instead of one, and the client doesn't understand how to handle it.
I am hitting the REST API server as a client using Swift 3 programming, I have sent request once and a single response. But the problem is once i posted my data's the data's are inserted twice and getting the response based on the second insert value.
For Example: When i posted new mail address, it inserted into Database, and it iterated again and trying to insert again and i get the response as "Email is already registered". I have tried all the methods from my client side programming.
Few have said that the server by itself restarted again after 40 sec, i'm not sure if that is the case how to overcome this problem.
CODE IN SWIFT 3 CLIENT:(iOS)
func getMailAddress(mailID: String) {
let username = "admin"
let password = "admin"
let loginString = String(format: "%#:%#", username, password)
let loginData: NSData = loginString.data(using: String.Encoding.utf8)! as NSData
let base64LoginString = loginData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let getUrl = URL(string: "http://localhost/rest/merchantsignup/mailExists/\(mailID)")
var request = URLRequest(url: getUrl!)
request.httpMethod = "GET"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let urlConnection = NSURLConnection(request: request, delegate: self)
urlConnection?.start()
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
} else {
do {
let myJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print("myJSON:\(myJSON)")
} catch let err as NSError {
print(err)
}
}
}
task.resume()
}
CODE IN JAVA REST WEBSERVICES:
#GET
#Path("/mailExists/{emailId}")
#Produces(MediaType.APPLICATION_JSON)
public RestResMessagesVO mailExists(#PathParam("emailId")String emailId){
System.out.println(emailId);
MerchantRegistrationDAO mcdao = new MerchantRegistrationDAO();
RestResMessagesVO resObj = new RestResMessagesVO();
resObj.setMessage(mcdao.ismcEmailorPhoneExists("emailAddress",emailId.trim()));
return resObj;
}
You are trying to establish a connection with basic authentication, but actual problem here, while your requesting your server it get hitted twice is
1. you established your connection using request so, by that time it hitted the server once.
2. Then you created an object for NSURLConnection, and you started the connection, by that it hits the server second time.
Because of this only you hit your server twice, and get the response based on the second server hit.
Solution: Try this to overcome your Problem:
let username = "admin"
let password = "admin"
let loginString = String(format: "%#:%#", username, password)
let loginData: NSData = loginString.data(using: String.Encoding.utf8)! as NSData
let base64LoginString = loginData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let getUrl = URL(string: "Your URL String")
var request = URLRequest(url: getUrl!)
request.httpMethod = "GET"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request)
{ (data, response, error) in
if error != nil
{
print(error!)
}
else
{
do {
let JSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print("YOUR RESPONSE: \(JSON)")
}
catch let err as NSError
{
print(err)
}
}
}
task.resume()
probably that's because you are calling
urlConnection?.start()
and
task.resume()
I have two ajax calls in my jsp code which go to servlet. In first call, I am setting a value in the session and in another call, I am retrieving the same value from the session. Now this value goes as response of the ajax call(2nd ajax call). My problem is:-
This value contains "\n"(eg-("ABC \n def\n geh \n xyz")) . When I store this value in a js variable and try to access it, it takes "\n" as string only. It is not recognising it as newline
ajax calls in jsp:-
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=datagrid",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
$('#contentDiv').show();
fillDataGrid(msg);
}
});
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=chart",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
fillDataChartData(msg);
}
});
code in servlet:-
HttpSession session = request.getSession();
String method = request.getParameter("method");
if(method.equalsIgnoreCase("datagrid"))
{
JSONArray listjson = CSR.firstcalledMethod();
String chartformat = CSR.callingMethod2();
System.out.println("chartformat in servlet = "+chartformat);
String result = listjson.toString();
String checkDataExists = (String) (session.getAttribute("chartformat") == null ? "Invalid" : session.getAttribute("chartformat"));
if(!checkDataExists.equalsIgnoreCase("Invalid"))
{
session.removeAttribute("chartformat");
}
session.setAttribute("chartformat", chartformat);
out.write(result);
}
else
{
String chartResult = (String) session.getAttribute("chartformat");
session.removeAttribute("chartformat");
out.write(chartResult);
}
now in the same jsp which contains the ajax calls shown above I am trying to access the variable as :-
function fillDataChartData(dataVAR) {
var chartdata = dataVAR;
alert("chartdata = "+chartdata);
}
Suppose the response in ajax contains data "APAC-OTHER,0.05 \n FCS,99.95"(i.e. dataVAR = "ABC \n DEF \n GHI" ). Now, when I am trying to alert it in the function fillDataChartData(dataVAR), it shows "APAC-OTHER,0.05 \n FCS,99.95" in alert but I want it like APAC-OTHER,0.05
FCS,99.95
How should I do that?? Please help...
It's strange. May be there are some hidden chars in your response? Anyway, you can try to replace linebreaks by br tags:
function fillDataChartData(dataVAR) {
var chartdata = dataVAR.replace(/\\n/gm, '<br>');
alert("chartdata = "+chartdata);
}
I have a function that is called when a button is clicked, this function sends an ajax request using jquery. On success I have some logical if and else if statements. The web server can only send 2 types of text responses. It can either be "Success" or "Error". But when testing for these two conditions they seem to fail. I have added an else statement and an alert to tell me what the server is sending but just as I expected, it is either "Success" or "Error", the way I programmed my servlet in the server, it can only send "Success" or "Error" as response. Moreover my alert is spitting out "Success" or "Error" please I dont understand what is wrong here. please help.
function deleteRecord(productID, description)
{
var errorMessage = '<td class="red-left">There was an error. Please try again.</td>';
var successMessage = '<td class="green-left">Product '+productID+' ('+description+') has been deleted sucessfully.</td>';
var data = "productID="+productID+"&description="+description+"&deleteProduct=true";
$.ajax({
type: "GET",
url: "deleteInventoryRecord.mpcs",
data: data,
cache: false,
success: function(info)
{
if(info == 'Success')//This does not work
{
$(".green-left").replaceWith(successMessage);
$("#message-green").fadeIn("slow");
$("#product-"+productID).remove();
}
else if(info == 'Error')//This does not work
{
$(".red-left").replaceWith(errorMessage);
$("#message-red").fadeIn("slow");
}
else//This works always but I dont need it
{
alert(info); //It always says "Success" or "Error"
}
},
dataType: 'text'
});
}
Here is the servlet code that sends the response:
private void deleteProduct(HttpServletResponse response, String productID) throws IOException
{
try
{
response.setContentType("text/html");
InventoryDAO iDao = new InventoryDAO();
if(iDao.deleteProduct(productID) == true)
response.getWriter().println("Success");
else
throw new RuntimeException("Error");
}
catch(ClassNotFoundException | IOException | SQLException | RuntimeException xcp)
{
response.getWriter().println("Error");
}
}
Going to take a shot in the dark here, and say that the server is sending the response in UTF8 with a BOM, and this is causing your comparisons to fail.
To confirm, try alert(info.length). It should be 7 for "Success" or 5 for "Error". If it is not, then you probably have a BOM.
Another thing to check of course is that there is no whitespace in the response - again, the length check will help verify this.
You can fix this by encoding your server-side scripts as "UTF8 without BOM", sometimes referred to as "ANSI as UTF8" depending on your editor. Alternatively, change your if blocks to:
if( info.match(/Success$/)) ...
else if( info.match(/Error$/)) ...
Your deleteProduct method sets content type "text/html", but you are sending plain text. This is likely to confuse jQuery, as it tries to guess the type of info based on the content type header sent. Either use "text/plain", or even better "application/json", so you may sent more info to the client.
I'm new to play and I am trying to post form data to my Play Action using JQuery. However, I'm getting "expected json" response from Action. I check the HTTP Headers to ensure that the data is being sent and it is so, where am I going wrong and how can I fix it.(Is there a better approach to this)
Script:
$(document).ready (function (){
$("form").submit (function (e) {
e.preventDefault();
$.post("/save",$(this).serialize(),function (data){
alert(data);
});
});
});
Action
public static Result save()
{
JsonNode json = request().body().asJson();
if (json == null)
return ok("expected json");
else
{
String value = json.findPath("video").getTextValue();
if (value == null)
return ok("did not find");
else
return ok(value) ;
}
}
routes
POST /save controllers.Application.save()
Both: Julien Lafont and dfsq are right, first: you are not serializing your form to JSON, second, as Julien stated, you don't need to... Using your current JS you can just use DynamicForm in your save action:
public static Result save() {
DynamicForm df = form().bindFromRequest();
String value = df.get("video");
if (value == null || value.trim().equals(""))
return badRequest("Video param was not sent");
// do something with the value
return ok(value);
}
BTW, don't use ok() for returning responses for wrong requests. You have many options: badRequest(), notFound(), TODO, and wild bunch of other Results, even raw: status(int), so you can read the status in jQuery without passing any additional reasons of fail.
If you really, really need to serialize form to JSON for any reason, let me know, I'll send you a sample.