0

I want to redirect user to another route if the code matches depending upon the values returned in the ajax success. Its working great now How do I write the script to redirect to the next route like redirect in php.

AJAX to check the code matches and its working great. What next

<script>
$("#codeModal form").submit(function(event) {
        event.preventDefault();
        var codetyped=$(this).find(".codeinput").val();
        $.ajax({
            type:"post",
            url:"{{request.route_url('testingajax')}}",
            data:{'codetyped':codetyped},
            success:function(res){
                alert(res);
            }
        });
        });
</script>

Here is the view config

@view_config(route_name='testingajax', renderer='json')
def hello(request):
    # return request.session['secretcode']
    # return request.params.get('codetyped')
    if int(request.params.get('codetyped')) == request.session['secretcode']:
        return 'Success'
    else:
        return 'Error'
Tara Prasad Gurung
  • 3,422
  • 6
  • 38
  • 76
  • 1
    maybe return the destination URL to the AJAX response, and then have the AJAX use `window.location.href` etc to go to that URL (Milanzor's answer below) – Don Cheadle May 20 '16 at 14:20
  • http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call?rq=1 <-- similar SO question with lots of attention – Don Cheadle May 20 '16 at 14:37

1 Answers1

3

I'm not into Python, but it seems you are returning either 'Success' or 'Error' to your Ajax call.

Within your Ajax success callback function, you could simply check the returned value and redirect from there.

success:function(res){
    // Test if there is a returned value in the res variable
    if(typeof res !== 'undefined'){

        // Check the res variable from a few options
        switch(res){
            case 'Success':
                window.location.href='/some-success-page.html';
            break;
            case 'Error':
                window.location.href='/some-error-page.html';
            break;
        }
    }
}
Milanzor
  • 1,920
  • 14
  • 22