Reputation: 593
I am trying to send 'ip' variable from home.html to my main app.py python file, I have tried many things and none of them worked, Here is what I'm working with:
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$.getJSON("https://api.ipify.org?format=json",
function(data) {
var ip = data.ip
console.log(ip)
})
</script>
@app.route("/ip", methods=["GET", "POST"])
def get_ip():
return render_template('home.html')
Upvotes: 0
Views: 74
Reputation: 593
I got it to work!, Here is the answer:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON("https://api.ipify.org?format=json",
function(data) {
ip = data.ip
dd = {'ip': ip}
// console.log(ip);
// console.log(dd);
$.ajax({
data: JSON.stringify(dd),
contentType: "application/json; charset=utf-8",
dataType: "json",
type : 'POST',
url : '/'
})
});
})
</script>
Upvotes: 1
Reputation: 21
If you just want to send the IP to the backend, then do the following. In JS:
$.ajax({
dataType: 'string',
url: '/',
data: {
ip: '2.2.2.2'
},
type: 'GET',
success: function (data) {
...
...
}
});
And, to receive the IP in Flask,
ip = request.args.get("ip")
Upvotes: 0