I dont understand how to implement the Deleting Requests in request dialog - javascript

I have read the document here
but I don't understand how should I implement it right.
In my facebook app I use apprequests from JS api like this:
function newInvite() {
var msg = document.getElementById('msg_look_id').value;
var receiverUserIds = FB.ui({
method: 'apprequests',
message: msg,
title: "Select friends to send your gift",
},
function (response) {
alert("IDS : " + response.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
then the user see the request in its app request icon (with the red numbers )
the user click it , but then how do I implement the delete request ?

When the user arrives at your app’s canvas page following a request, there is a parameter called request_ids passed to your app.
Since Facebook calls apps in the iframe using the HTTP method POST, I guess this is also a POST parameter (although it is not explicitly mentioned in the docs). That means you have no access to it using pure client-side JavaScript; you have to use a server-side script to get the content of this parameter.

Related

PUT and POST Request of .save() of Backbonejs model

How to be confirmed whether a backbonejs .save() is sending PUT request ?? I checked my server side, which is working good, there is no problem in server side. But my .save() is not working.
Here is my model of backbone
define(['underscore','backbone'],function(_,Backbone)
{
var my_model = Backbone.Model.extend(
{
urlRoot: "http://localhost/back/server_file.php/number"
});
return my_model;
});
Here is how I am using .save()
var my_data = {
id: data.id,
code: data.code
};
var My_model = new my_model();
My_model.save(my_data,
{
success: function(response)
{
alert('Yes');
},
error: function(response)
{
alert('No');
}
});
I think my .save() is sending POST request to server.
UPDATE
I think I could find out my problem. I am describing that here.
What I would like to do
I would like to send 2 parameters from backbonejs model to server side script (I am using PHP SLIM Framework). Based on those 2 parameters server side script update a record's(2 field of this record match with those 2 parameters ) another field with a static parameter at database.
What backbonejs provide (As I think )
Backbonejs has a model with id as JSON format. Backbonejs sends PUT request to server side script. Server side script just dump (update) the data(which was as JSON format,like a bundle) to the database with matching id. Serer side script would not like to look inside the data.
I am getting (from network tab of firebug) my PUT request URL is like http://localhost/back/server_file.php/number/1 (This is the id) . On the other hand I would like to get URL is like http://localhost/back/server_file.php/number/1 (id the first parameter)/456 (Second parameter).
If I am right, anyone could say how can I implement my plan??
This should work,
My_model.set(my_data);
My_model.save(null, {
wait : true,
url : "http://localhost/back/server_file.php/number/1/456",
success : function(response){
},
error : function(e){
}
});
You can debug the request being sent in network tab of Chrome Developer Tools or you can use a network tool like Fiddler to see all requests.
Refer the attached on where to see the request method being used.

400 Error on AJAX Call to Twitter

I'm working on a web page that lets you search for twitter users in your area. You enter a name in the search box and it returns users with that name within 50 miles of the city (the city is always the same).
I was having trouble authenticating, and I found oauth.io. I used that to authenticate and it seems to be working. But when I do a search, my request to Twitter returns as a 400 bad request error. I'm not sure what I'm doing wrong. I've looked at the oauth.io documentation but couldn't find anything.
Here is the part of the code that gets the value of what the user entered into the form field:
// Click function
$('.user-getter').submit(function(event) {
// prevent form refresh
event.preventDefault();
// zero out results if previous search has run
$('.user-results').html('');
// Get the values of what the person entered in search
var query = $(this).find("input[name='user_search']").val();
// Run function to send API request to Twitter
getUser(query);
}); // end click function
Here is the part of the code that calls the authorization and then sends the ajax request:
var getUser = function(query) {
OAuth.initialize('oMQua1CuWerqGKRwqVkzDx5uijo')
OAuth.popup('twitter').done(function(twitterData) {
$.ajax({
type: "GET",
url: "https://api.twitter.com/1.1/users/search.json?&geocode=42.94003620000001,-78.8677924,50mi&q=" + query,
dataType: "jsonp"
});
console.log( "Data Saved: " + twitterData ); // can see in inspector tab under Network
}); // end oAuth popup
};
Right now, I just want to see the result in console.log.
To make a request to Twitter API using OAuth.io you have to use the OAuth.io Javascript SDK instead of directly $.ajax (the OAuth.io Javascript SDK use the syntaxe of $.ajax behind the scene)
OAuth.initialize('oMQua1CuWerqGKRwqVkzDx5uijo')
OAuth.popup('twitter').done(function(twitterData) {
twitterData.get('/1.1/users/search.json', {
data: {
q: query
}
}).done(function(search) {
//result of the search here
console.log(search);
}).fail(function(error) {
//error management here
});
})
The SDK does all the hard things for you transparently: proxy the HTTP request, inject all the needed OAuth credentials (oauth_token, oauth_token_secret, signature, nonce, timestamp etc..)
Take a look to this jsfiddles: http://jsfiddle.net/uz76E/10/
I hope that helps,

How do I check if a user has accepted my application request in facebook?

I send my app request using the following method
function sendRequest() {
FB.ui({method: 'apprequests',
message: 'You have received a pretty image from a friend.',
data: 'some tracking info',
title: 'Select friends to send your image to.'}, function (response) {
if (response && response.request_ids) {
$(function(){
//get friends who accepted the request
} else {
//Do something if they don't send it.
}
})
}
However, I have no idea how to check if any friends have accepted the request ?
Any idea how to do that?
I also want to get a notification when a user accepts the request ...How do I achieve that?
You need to save the response.request_ids and then you can use open graph to query information on those requests. Get an access/auth token using app login, then query the graph api:
https://graph.facebook.com/[request_id]?access_token=[token]
But even without doing that, you should just be recording that the user responded when they click on the "invite". Facebook passes a request_ids parameter in the URL. You should check for that when a user comes to your app. Then you can update your information that the user responded to the request.

AD FS 2.0 Authentication and AJAX

I have a web site that is trying to call an MVC controller action on another web site. These sites are both setup as relying party trusts in AD FS 2.0. Everything authenticates and works fine when opening pages in the browser window between the two sites. However, when trying to call a controller action from JavaScript using the jQuery AJAX method it always fails. Here is a code snippet of what I'm trying to do...
$.ajax({
url: "relyingPartySite/Controller/Action",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});
The issue is that AD FS uses JavaScript to post a hidden html form to the relying party.
When tracing with Fiddler I can see it get to the AD FS site and return this html form which should post and redirect to the controller action authenticated. The problem is this form is coming back as the result of the ajax request and obviously going to fail with a parser error since the ajax request expects json from the controller action. It seems like this would be a common scenario, so what is the proper way to communicate with AD FS from AJAX and handle this redirection?
You have two options.
More info here.
The first is to share a session cookie between an entry application (one that is HTML based) and your API solutions. You configure both applications to use the same WIF cookie. This only works if both applications are on the same root domain.
See the above post or this stackoverflow question.
The other option is to disable the passiveRedirect for AJAX requests (as Gutek's answer). This will return a http status code of 401 which you can handle in Javascript.
When you detect the 401, you load a dummy page (or a "Authenticating" dialog which could double as a login dialog if credentials need to be given again) in an iFrame. When the iFrame has completed you then attempt the call again. This time the session cookie will be present on the call and it should succeed.
//Requires Jquery 1.9+
var webAPIHtmlPage = "http://webapi.somedomain/preauth.html"
function authenticate() {
return $.Deferred(function (d) {
//Potentially could make this into a little popup layer
//that shows we are authenticating, and allows for re-authentication if needed
var iFrame = $("<iframe></iframe>");
iFrame.hide();
iFrame.appendTo("body");
iFrame.attr('src', webAPIHtmlPage);
iFrame.load(function () {
iFrame.remove();
d.resolve();
});
});
};
function makeCall() {
return $.getJSON(uri)
.then(function(data) {
return $.Deferred(function(d) { d.resolve(data); });
},
function(error) {
if (error.status == 401) {
//Authenticating,
//TODO:should add a check to prevnet infinite loop
return authenticate().then(function() {
//Making the call again
return makeCall();
});
} else {
return $.Deferred(function(d) {
d.reject(error);
});
}
});
}
If you do not want to receive HTML with the link you can handle AuthorizationFailed on WSFederationAuthenticationModule and set RedirectToIdentityProvider to false on Ajax calls only.
for example:
FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += (sender, e) =>
{
if (Context.Request.RequestContext.HttpContext.Request.IsAjaxRequest())
{
e.RedirectToIdentityProvider = false;
}
};
This with Authorize attribute will return you status code 401 and if you want to have something different, then you can implement own Authorize attribute and write special code on Ajax Request.
In the project which I currently work with, we had the same issue with SAML token expiration on the clientside and causing issues with ajax calls. In our particular case we needed all requests to be enqueud after the first 401 is encountered and after successful authentication all of them could be resent. The authentication uses the iframe solution suggested by Adam Mills, but also goes a little further in case user credentials need to be entered, which is done by displaying a dialog informing the user to login on an external view (since ADFS does not allow displaying login page in an iframe atleast not default configuration) during which waiting request are waiting to be finished but the user needs to login on from an external page. The waiting requests can also be rejected if user chooses to Cancel and in those cases jquery error will be called for each request.
Here's a link to a gist with the example code:
https://gist.github.com/kavhad/bb0d8e4a446496a6c05a
Note my code is based on usage of jquery for handling all ajax request. If your ajax request are being handled by vanilla javascript, other libraries or frameworks then you can perhaps find some inspiration in this example. The usage of jquery ui is only because of the dialog and stands for a small portion of the code which could easly be swapped out.
Update
Sorry I changed my github account name and that's why link did not work. It should work now.
First of all you say you are trying to make an ajax call to another website, does your call conforms to same origin policy of web browsers? If it does then you are expecting html as a response from your server, changedatatype of the ajax call to dataType: "html", then insert the form into your DOM.
Perhaps the 2 first posts of this serie will help you. They consider ADFS and AJAX requests
What I think I would try to do is to see why the authentication cookies are not transmitted through ajax, and find a mean to send them with my request. Or wrap the ajax call in a function that pre authenticate by retrieving the html form, appending it hidden to the DOM, submitting it (it will hopefully set the good cookies) then send the appropriate request you wanted to send originally
You can do only this type of datatype
"xml": Treat the response as an XML document that can be processed via jQuery.
"html": Treat the response as HTML (plain text); included script tags are evaluated.
"script": Evaluates the response as JavaScript and evaluates it.
"json": Evaluates the response as JSON and sends a JavaScript Object to the success callback.
If you can see in your fiddler that is returning only html then change your data type to html or if that only a script code then you can use script.
You should create a file anyname like json.php and then put the connection to the relayparty website this should works
$.ajax({
url: "json.php",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});

jQuery Get Request on HTTP URL

i've recently tried to get some Response from an URL using jQuery. Therefore I copied a get request sample of jQuery API Get Request Tutorial into my project and tried to run it, but my debugging messages showed me, that it can't go further. I tried the javascript Ajax Library using a simple request, but it didn't work.
So i'm asking you, if you could help me somehow.
And this is all what i do, but there is no response.
var url = "http://www.google.com";
$.get(url, function(data){
alert("Data Loaded: " + data);
});
Did i probably forgot to include a ajax or jQuery library. For a better understanding, i have c and obj-c experince, this is why i think, that a library is missing.
In each sample there is just a short url like "test.php". Is my complete HTTP url wrong?
Thanks for your answers in advanced.
Br
Nic
I have provided an example scenario to help get you started:
<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script
This is probably best to include inside of an external JS file:
//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
$.ajax({
//The URL to process the request
'url' : 'page.php',
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type' : 'GET',
//Any post-data/get-data parameters
//This is optional
'data' : {
'paramater1' : 'value',
'parameter2' : 'another value'
},
//The response from the server
'success' : function(data) {
//You can use any jQuery/JavaScript here!!!
if (data == "success") {
alert('request sent!');
}
}
});
});
You're hitting the Same Origin Policy with regard to ajax requests.
In a nutshell, JS/Ajax is by default only allowed to fire requests on the same domain as where the HTML page is been served from. If you intend to fire requests on other domains, it has to support JSONP and/or to set the Access-Control headers in order to get it to work. If that is not an option, then you have to create some proxy on the server side and use it instead (be careful since you can be banned for leeching too much from other sites using a robot).
As others have said you can't access files on another server. There is a hack tho. If you are using a server side language (as i assume you are) you can simply do something like:
http://myserver.com/google.php:
<?php
echo get_file_contents('http://www.google.com');
?>
http://myserver.com/myscript.js
$.get('google.php',function(data){ console.log(data) });
That should work!
you just can access pages from your domain/server

Categories

Resources