6

I try to redirect to a new page after ajax post but I have not been successfull yet.

My template looks like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
 $(function() {

     var selectedForm = 0;

     function doWork() {
         var response = $('#reply1').val();
         console.log(response);
         $.post({url: "receiver", data: JSON.stringify({selectedForm: selectedForm, response : response}),
                 contentType: "application/json", success: function(){}});
     }

     $('.respondButton').click(function(e) {
         e.preventDefault();
         var selectedButton = $(this).attr('id');
         selectedForm = selectedButton.replace('response', '');
         console.log(selectedForm);
     });

     $('#submitButton1').click(function(e) {
         e.preventDefault();
         doWork();
     });

 });
</script>

Html part:

<a id="response1" href="" class="respondButton">
    <span>response1</span>
</a>

<a id="response2" href="" class="respondButton">
    <span>response2</span>
</a>

<form  action="/receiver" method="post" id="form1" name="form1">
    <textarea type="text"  rows ="3" name="reply1" id="reply1"></textarea>
    <button type="submit"  name="submitButton1" id="submitButton1">Submit</button>
</form>

And on the server side flask application looks like this:

#!flask/bin/python

import sys

from flask import Flask, render_template, request, redirect, Response, url_for
import random, json

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/somepage')
def somepage():
    return 'Success'


@app.route('/receiver', methods = ['POST'])
def worker():

    data = request.get_json()
    result = ''
    result = str(data)

    print(result)

    return (redirect(url_for('somepage')))


if __name__ == '__main__':

    app.run(debug=True)

When I open Chrome developer tools and click network it looks fine and I may see success message but stil browser doesn't redirects to /somepage

1 Answers1

6

As I see in your flask application you try to output the data and redirect to home page, but the application will execute the output part which is the message and will not continue to the redirect, if you need to make a redirect, you should do it in ajax call.

success: function(){
    window.location.href = "somepage";
}
Espoir Murhabazi
  • 5,973
  • 5
  • 42
  • 73
samehanwar
  • 3,280
  • 2
  • 23
  • 26
  • I was trying to send comment and refresh page. You may see a live demo [here](http://programlama.herokuapp.com/soru/1) Thanks. –  Nov 05 '17 at 18:10