Flask redirect after ajax request success - redirect

I develop a mapping app, the front-end is created with Flask. When searching the external backend (create with the django framework) with ajax requests. I would like redirect the url after return from the ajax response (if success or not). But, I don't know the best way for this !
submitHandler: function () {
/********* GET USER TOKEN WITH AJAX REQUEST**********/
$.ajax({
method: 'POST',
url: "url for get token",
data: {
username: $('#email-log').val(),
password: $('#password-log').val()
},
success: function (response) {
if(response.d == true) {
localStorage["username"] = $('#username-log').val();
localStorage["user_token"] = response['token'];
window.location = "{{url_for('maps')}}";
}
},
});
},
Where do I do this redirection?
In ajax request, in the form action = "", using url_for() somewhere ?
I'm lost in all these methods

If you only want to redirect after Ajax success you can do this:
$.ajax({
// do what you want,
success: function(){
window.location.href = "/url/for/route/" //redirect url
// or
window.location.replace("url/for/route")
}
});

Related

elgg api auth and user auth in header for REST?

hi I am new to elgg REST API.
I want to login and add post to wire for that I have method=wire.save_post
I learned from Google that api auth and user auth must be given in request header how?
I am doing a ajax for adding post to wire :
$("#post_text").submit(function() {
$.ajax({
type:"POST",
url:"http://elgg.amusedcloud.com/services/api/rest/json/?",
data:{ method:'wire.save_post', text : text_val, access : 'public', wireMethod : 'site', username : uname },
dataType:"json",
success: function(data) {
}
});
});
Normally an ajax call to the elgg webservice you are referring to should look something like this. Note that the api_key and auth_token are part of the request URL.
$("#post_text").submit(function() {
$.ajax({
type:"POST",
url:"http://elgg.amusedcloud.com/services/api/rest/json/?method=wire.save_post&api_key=1140321cb56c71710c38feefdf72bc462938f59f&auth_token=df123dfgg455666",
data:{
text : text_val,
access : 'public',
wireMethod : 'site',
username : uname
},
dataType:"json",
success: function(data) {
}
});
});
You didn't mention this but, when you say
... I learned from Google that api auth and user auth must be given in request header
is this in the context of using OAuth as an authentication mechanism? In which case, you will have to use the HTTP header Authorization to send the hash and signature. The above call would then be like this.
$("#post_text").submit(function() {
$.ajax({
type:"POST",
url:"http://elgg.amusedcloud.com/services/api/rest/json/?method=wire.save_post&auth_token=df123dfgg455666",
data:{
text : text_val,
access : 'public',
wireMethod : 'site',
username : uname
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-Test-Header', 'test-value');
},
dataType:"json",
success: function(data) {
}
});
});
Note the changes in the url and addition of beforeSend property to the ajax object.
References:
http://docs.elgg.org/wiki/OAuth
http://api.jquery.com/jQuery.ajax/

Get public feeds of a Facebook Page in Node.js

I'm developing a simple node/express/jade website that fetch all the public feeds of a Facebook Page.
I create an application from wich i get client_id (APP_ID) and client_secret (APP_SECRET).
My code works, and it's okay but i wonder if this is the correct way of handling this need.
Here is the code:
var https = require('https'),
concat = require('concat-stream'),
async = require('async');
function FacebookPage(pageId) {
if (!(this instanceof FacebookPage))
return new FacebookPage(pageId);
this.pageId = pageId;
}
FacebookPage.prototype.getPublicFeeds = function (callback) {
var pageId = this.pageId;
async.waterfall([
function (done) {
var params = {
hostname: 'graph.facebook.com',
port: 443,
path: '/oauth/access_token?client_id=MY_CLIENT_ID&' +
'client_secret=MY_CLIENT_SECRET&grant_type=client_credentials',
method: 'GET'
};
https.get(params, function (response) {
//response is a stream so it is an EventEmitter
response.setEncoding("utf8");
//More compact
response.pipe(concat(function (data) {
done(null, data);
}));
response.on("error", done);
});
},
function (access_token, done) {
var params = {
hostname: 'graph.facebook.com',
port: 443,
path: '/v2.0/' + pageId + '/feed?' + access_token,
method: 'GET'
};
https.get(params, function (response) {
//response is a stream so it is an EventEmitter
response.setEncoding("utf8");
//More compact
response.pipe(concat(function (data) {
callback(null, JSON.parse(data));
}));
response.on("error", callback);
});
}]);
};
module.exports = FacebookPage;
EDIT: thank to #Tobi I can delete the part of getting the access_token by putting access_token=app_id|app_secret as explained here:
Not sure why you'd want to include to OAuth stuff (which I think can't work because you don't exchange the code for an actual access token if I understand this correctly)...
According to https://developers.facebook.com/docs/graph-api/reference/v2.0/page/feed/ you need an access token ... to view publicly shared posts., this means you can also use an app access token in the form of app_id|app_secret.
You can then use the
GET /{page_id}/feed
endpoint by passing the access_token paramenter with your app access token. I'd also recommend to use the NPM modules request or restler, these make the HTTP handling much easier.

How to serve 404's using AngularJS and a RESTful API

Let's say you have an AngularJS application hooked up to a RESTful API and you have a route for "/item/:itemId".
.when('/item/:itemId', {
templateUrl: '/static/partials/item-detail.html',
controller: ItemDetailController
})
angular.module('angServices', ['ngResource']).factory('Item', function($resource) {
return $resource('/api/item/:itemId', {}, {
query: { method: 'GET', params: { itemId: '' }, isArray: true }
});
});
If the user goes to "/item/9" and an object with the itemId 9 does not exist, Angular will receive a 404 from the API, but will not naturally return a 404 to the user.
In other questions, I've seen people suggest creating an interceptor and having Angular redirect to a 404 error page when a resource is not found.
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
However, I want to return a correct 404 with the original requested URL for SEO purposes.
Also, the solution above first loads the page and then redirects (just like Twitter used to do), so its sub-optimal.
Should I check server-side to first see if the resource exists before passing the request on to the Angular app? The downside of this is that it wouldn't work for broken links within the application.
What is the best way to approach this?
Maybe this jsfiddle can help you.
http://jsfiddle.net/roadprophet/VwS2t/
angular.module('dgService', ['ngResource']).factory("DriveGroup", function ($resource) {
return $resource(
'/', {}, {
update: {
method: 'PUT'
},
fetch: {
method: 'GET',
// This is what I tried.
interceptor: {
response: function (data) {
console.log('response in interceptor', data);
},
responseError: function (data) {
console.log('error in interceptor', data);
}
},
isArray: false
}
}
);
});
var app = angular.module('myApp', ['ngResource', 'dgService']);
app.controller('MainController', ['$scope', 'DriveGroup', function ($scope, svc) {
$scope.title = 'Interceptors Test';
svc.fetch(function (data) {
console.log('SUCCESS');
}, function () {
console.log('FAILURE');
});
}]);
I tried with this and works fine. I only change the fetch method to get.
In your case, you will need to change the console.log('FALIURE'); to $location.path('/404');.
GL!

making jquery AJAX POST to resful API

I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.
The REST API code:
#Path("/track")
public class TrackResource {
...
The method in TrackResource class i'm trying to hit :
#POST
#Path("{trackid}")
#Consumes("application/json")
#Produces("application/json")
public Response addToResource(#PathParam("trackid") String trackid, String bodyJson) {
The AJAX code:
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.
I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.
If you're posting a JSON string make sure you also set contentType: "application/json".
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I needed to use the router address of my computer, 192...., in order to hit my localhost... I was running the application on an actual Android device, however, I guess trying to use localhost or 127.0.0.1 in the AJAX call must have been causing issues.

How to cancel likes on other site

When you click the Like button https://graph.facebook.com/object_id/likes calls.
To cancel the Like what should I do?
I tried the following:
<code>
<script>
function doLike(objectId) {
$.ajax({
url: 'https://graph.facebook.com/'+objectId+'/likes',
type: 'post',
data: {
access_token: '....'
}
});
}
function doCancel(objectId) {
$.ajax({
url: '???',
type: 'post',
data: {
access_token: '....'
}
});
}
</script>
<input onclick="doLike('...')">Like</button>
<input onclick="doCancel('...')">Cancel</button>
</code>
This drove me nuts. Firefox/Chrome and probably everything else apparently won't allow HTTP DELETE ajax calls unless the host has previously communicated during the current request. So $.ajax{(type: 'delete', ... )} works for YOUR server url host but not anything else.
The workaround is something like:
$.ajax({
url: "https://graph.facebook.com/" + FB_ACTION_ID,
type: 'post',
data: { access_token: ACCESS_TOKEN,
'method': 'delete',
'_method' : 'delete' }
})
If you're looking for an API which allows you to remove a Like of a Facebook page, this is not possible.
If you're looking for an API to remove a Like of an object (via URL) - you can make a HTTP DELETE request to /LIKE_INSTANCE_ID which is the ID returned to your app when you posted the Open Graph like - otherwise it's not possible
You should be able to "unlike" an object ID simply by doing a HTTP DELETE. Using your code, it'd look something like this:
function doCancel(objectId) {
$.ajax({
url: 'https://graph.facebook.com/'+objectId+'/likes',
type: 'delete',
data: {
access_token: '....'
}
});
}
Alternatively, use the Facebook Javascript SDK, in which you can simply do:
FB.api("/" + objectId + "/likes", 'delete', callback);
where callback is the function to call when the unlike operation is complete.