Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Flask's render_template from an ajax POST form submit

I am hoping to get an answer to this similar question:

I have a jQuery form that sends JSON data to a certain URL that is served by Flask:

    <div id="form">      
      <form id="send">        
        <input type="submit" value="Continue" >
      </form>
    </div>



jQuery(document).on('ready', function() {
        jQuery('form#send').bind('submit', function(event){
        event.preventDefault();

        var form = this;
        json = geojson.write(vectors.features);

        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: $SCRIPT_ROOT + "/create",
            dataType: "json",
            success: function(){},
            data: json

        });
    });
});

On the Flask side, I have a simple function that renders an HTML page displaying the JSON object:

@app.route('/create', methods=['POST'])
def create():
    content = request.json
    print content
    return render_template('string.html', string = content)

I know the JSON is being passed, because I can see it printed in the console running the Flask server:

console print

The problem is that the template is rendered as part of the response of the Ajax request, but I want the template to be rendered as a new html page:

response of request

like image 896
camdenl Avatar asked Feb 12 '23 10:02

camdenl


2 Answers

try this,

$.ajax({
        type: "POST",
        contentType: 'application/json',
        url: $SCRIPT_ROOT + "/create",
        dataType: "json",
        success: function(){},
        data: json
        success:function(response){
            document.write(response); 
       }

    });
like image 174
hari Avatar answered Feb 14 '23 23:02

hari


So it turns out I actually didn't need to use jQuery for this, instead I can submit JSON simply using an html form with a hidden field (as hinted at in this question):

<div id="form">

      <form id="send" method="post" action="create" onsubmit="getJSON()" enctype='application/json'>        
        <input type="submit" value="Continue" />
        <input type="hidden" name="jsonval" value=""/>
      </form>
</div>

And then use javascript to populate the form when the button is clicked:

function getJSON(){

            json = geojson.write(vectors.features);
            var formInfo = document.forms['send'];
            formInfo.jsonval.value = json;

        }
like image 25
camdenl Avatar answered Feb 14 '23 23:02

camdenl