Search code examples
jquerypythonajaxpyramidhttp-redirect

Pyramid HTTP redirect after AJAX post


Is it possible to redirect to another page after a jquery post to the server? Once the user logs in, I want to return a json response or redirect to another page. I know the correct view callable is being called, because I can see a log statement from the server.

Here's my jquery post:

function postToServer(url, params) {
    $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(params),
        contentType: 'application/json; charset=utf-8',
        statusCode: {
            200: function (data, textStatus, jqXHR) {
                return data;
            },
            201: function (data, textStatus, jqXHR) {
                return data;
            },
            400: function(data, textStatus, jqXHR) {
                return data;
            }
        }
    });
}

It's pretty basic and seems to work well. Whenever I return json, it handles the response correctly.

Here are my views:

#LOGIN
class LoginView(object):
    def __init__(self, request):
        self.request = request
        self.ctx = core.context()

    @view_config(route_name="login", request_method='GET')
    def get(self):
        template = "project:templates/login/login.mak"
        context = {}
        return render_to_response(template, context, request=self.request)

    @view_config(route_name="login", request_method='POST')
    def post(self):
        url = self.request.route_url('dashboard')
        print 'url: ' + url        
        #log user in and get credentials

        json = getJsonCredentialsObject()
        return Response('json', json)

#DASHBOARD
class DashboardView(object):
    def __init__(self, request):
        self.request = request
        self.ctx = core.context()

    @view_config(route_name="dashboard", request_method='GET')
    def get(self):
        print "in dashboard"
        template = "project:templates/dashboard/dashboard.mak"
        session = self.request.session
        context = {}
        return render_to_response(template, context, request=self.request)

I'd like the post method in the Login class to handle the interaction, but when I try to redirect here using "return HTTPFound(location=self.request.route_url('/dashboard'))" nothing happens. I'm also having trouble getting the request.json_body object out of the request (it's null), but that's another issue. Thanks for any help.


Solution

  • I think to achieve what you want you can't return pyramid Redirect to ajax call.

    Return json data with the status and redirect url

    Then on front end you can redirect user on success

    window.location = http://redirecturlhere