-1

!! THIS IS NOT A DUPLICATE !!

The question was not how to get an URL in Flask, but how to send data with jQuery to Flask!

I try to send and receive data with python, Flask and jQuery The problem is that I want the full URL of the website and it is impossible to get it with flask because I make 'POST' requests. So with jQuery, I want to send the current URL. I don't know how to send data (with jQuery) and receive data (with Flask).

Python/Flask code:

@app.route('/invisible', methods = ['POST'])
def dynamic_refresh():
    return jsonify({'somedata': 'data'})

HTML/jQuery code:

<script>
$(document).ready(function() {
    window.setInterval(function() {
        $.ajax({
            type : 'POST',
            url : '/invisible',
            //I tried to send data from here but it didn't worked
        })
        .done(function(data) {
            console.log(data)
            console.log(window.location.href)//the url I want to send
            //here I use the data received by the server
        })
    }, 5000);
});
</script>
my_name
  • 87
  • 1
  • 1
  • 11

1 Answers1

3

Its quite simple, enclose data in JSON array which you want to send through POST request and then retrieve any data from Flask endpoint like this;

var url = $('#url').val().trim();  //get your value from HTML here                
var params = {
    _url: url,
};
var array = JSON.stringify(params); //enclosed it in json array

$.ajax({
    type: "POST",
    url: "/invisible",
    data: array,
    dataType: 'json',
    success: function(results){
        console.log(results)
    }
});
Saad
  • 916
  • 1
  • 15
  • 28
  • Can you explain a little bit your code, and where I write it? I'm new to jQuery! How do I get the JSON in Flask? – my_name Sep 12 '18 at 08:20
  • Your objective or Goal is still not cleared to me, what you are trying to achieve ? – Saad Sep 12 '18 at 08:22
  • I want to send the current URL (window.location.href) with jQuery, to my Flask function. The jQuery I currently use is to receive data from Flask. If possible I want to send the URL in the same jQuery function. – my_name Sep 12 '18 at 08:27
  • get you current URL in any variable, var current_url = window.location.href , embed this variable along with the JSON you are posting in ajax POST request. As i have shown you in the code that how to send data via ajax POST request. – Saad Sep 12 '18 at 08:36
  • It doesn't work, I receive None values! – my_name Sep 12 '18 at 08:52
  • you receive no values in your flask function ? – Saad Sep 12 '18 at 08:53
  • make your flask function like this to receive value; `content = request.json` and then retrieve it from content like this `your_url = content['_url']` – Saad Sep 12 '18 at 08:56
  • Ok thank you! It was another problem, now it works! – my_name Sep 12 '18 at 08:58