0

I'm having a bit of trouble with figuring out how to get a post from Javascript to work, to my Python Flask server.

Here's the important part of what I've got in my html file

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js </script>
<script type=text/javascript>
    $('a#test').bind('click', function() {
        var textBox = document.getElementById('targetTextArea').value;
        $.post('/postmethod', {text: textBox} );
    });
</script>

<!--textarea-->
<textarea rows="1" cols="20" id="targetTextArea">
</textarea>

<!--button-->
<form method="post" role="form">
<a href=# id=test>
    <input type="button" value="submit" id="submit" onClick="writeOut()">
</a>
</form>

and here's what I've got in my Python flask file

@app.route('/postmethod', methods = ['POST'])
def postmethod():
    data = request.form['text']
    print "Hello world!"
    print data
    return data

When I run my python script the textarea and button are there as they should be, but when I type into the textarea and click the button nothing is printed. Please help.

1
  • you also don't need to add method="post" to your <form> tag because the jQuery code already calls $.post(...) Commented Feb 7, 2019 at 17:21

3 Answers 3

1

You try with the long way? Replace $.post('/postmethod', {text: textBox} ); for

$.ajax({
        method: "POST",
        url: "postmethod", //here can be '/postmethod'
        dataType: 'text',
        data: {text: textBox},
        success: function(result) {
            // example
            $('body').html(result)
        }
});

This should print on page the content of the variable "data" of python code.

Another thing,

I see that you are using two ways for the submit button, if you use

$('a#test').bind('click', function() { //code });

then, the onClick="writeOut()" is not neccessary.

I hope you find it useful, regards.

Sign up to request clarification or add additional context in comments.

Comments

0

id's value should be in quotes

<a href="#" id="test">
        <input type="button" value="submit" id="submit" onClick="writeOut()">
    </a>

Comments

0

The solution I found was to add

$(function() {
});

around it

$(function() {
    $('a#test').bind('click', function() {
        var textBox = document.getElementById('targetTextArea').value;
        $.post('/postmethod', {text: textBox} );
        return false;
    });
});

and also the return false prevents the page of redirecting

sorry guys, I'm new to Javascript. Thank you very much!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.