How to do a post to flask from a button - javascript

How do I make a post request from java to flask?
Why can I get the data sent to the server?
<button name="send" id = "sendbutton">Send</button>
document.getElementById("sendbutton").addEventListener('click', () => {
var image = canvas.toDataURL();
var r = new XMLHttpRequest();
r.open("POST", "http://127.0.0.1:5000/truthMask", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
//alert("Success: " + r.responseText);
console.log("sent");
};
r.send(input="test");
});
#app.route('/truthMask', methods=['POST'])
def set_truthMask():
print("Got the data")
foo = request.args.get("input")
print("Print the data: {}".format(foo))
return "sent"

JS Code
document.getElementById("sendbutton").addEventListener('click', () => {
var image = canvas.toDataURL();
var r = new XMLHttpRequest();
r.open("POST", "http://127.0.0.1:5000/truthMask", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
//alert("Success: " + r.responseText);
console.log("sent");
};
// Send data in below way from JS
r.send(JSON.stringify({"input": "test"}));
});
Python Flask API
import json
#app.route('/truthMask', methods=['POST'])
def set_truthMask():
print("Got the data")
foo = json.loads(request.data.decode())["input"]
print("Print the data: {}".format(foo))
return "sent"
Don't forget to import json

Related

Javascript GET request after POST request

I have a page that uses a function for getting some data, with a GET xhttp request, from a database (get_worktime_list()).
On the same page, I can add some data to the database with a form using a POST xhttp request and after a success (saved in the response) I will get the content included the new line from the database with the same function get_worktime_list().
The problem is that when getworktime is called after the POST request, get_worktime_list() makes another POST request instead of a GET. why???
function http_request(post_data, end_point, type)
{
console.log("HTTP");
var res = 0;
//var data = "data=0&username="+stored_token.username+"&token="+stored_token.token;
var data = "data=0&"+post_data;
console.log(data);
// Check if is valid token/username from database
const url = "http://192.168.1.188:5000/services/"+end_point;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(xhttp.responseText);
}
};
if (type == "GET")
{
console.log(url+"?"+post_data);
xhttp.open("GET", url+"?"+post_data, false);
}
else
{
console.log("Data: "+data);
xhttp.open("POST", url, false);
}
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(data);
xhttp.abort();
return res;
}
This add data to DB
function addworktime(username,token)
{
console.log("Aggiungo ore");
var date = document.getElementById("data").value;
var type = document.getElementById("turno").value;
var pay = document.getElementById("paga").value;
var emp = document.getElementById("dipendente").value;
var ore = document.getElementById("num_ore").value;
var data = "username="+username+"&token="+token+"&day="+date+"&turn_type="+type+"&pay="+pay+"&emp="+emp+"&ore="+ore;
var res = http_request(data,"admin/dipendenti/addtime.php","");
//console.log(res);
if (res.insert_ok == 1)
{
display_time_table(0,0,null);
} else {
console.log(res);
}
}
This function makes a GET request when a page load and a POST request when called by addworktime()
function display_time_table(from,to,cf)
{
let time_list_table = document.getElementById("list-container");
var time_list = get_worktime_list(saved_data.username,saved_data.token,from,to,cf);
let time_table = generate_time_list_table(time_list);
time_list_table.innerHTML = time_table;
}
function get_worktime_list(username,token,date_from,date_to,cf)
{
var data = "username="+username+"&token="+token;
if (cf != "" || cf != null)
{
data = data+ "&dipendente="+cf;
}
if (date_from != 0)
{
data = data +"&date_from="+date_from;
}
if (date_to != 0)
{
data = data + "&date_end="+date_to;
}
var time_list = http_request(data,"admin/dipendenti/getworktime.php", "GET");
return time_list;
}
The server can only accept GET requests for that API and obviously, I get a parse error parsing the JSON response.
Thanks for help

Sending location to the database directly

I have a script that allows to get the position (latitude & longitude) and after that it gets inserted in the input!
<script>
function maPosition(position) {
var x = position.coords.latitude;
var y= position.coords.longitude;
document.getElementById("x").value=x;
document.getElementById("y").value=y;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(maPosition);
}
</script>
this is the result looks like!!
I want to, when the user allows the permission to get his position, the script automatically send the position (x,y) to the database without putting the position in the input (because I couldn't the position without putting them in the input)!!!
this is my script in NodeJs :
<script>
function ajouter() {
var url = "http://127.0.0.1:3000/reclamations";
var data = { };
data.location="X = "+document.getElementById("x").value;
data.location+="Y = "+document.getElementById("y").value;
var json = JSON.stringify(data);
console.log(json);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
alert(" added !");
}
else {
console.table(users);
}
}
xhr.send(json);
}
</script>
Your code is very close, I added a button to make it easier to run here.
const ajouter = position => {
const url = "http://127.0.0.1:3000/reclamations";
// data is an object
let data = {};
// there are two properties - x and y which represent latitude and longitude
data.x = position.coords.latitude;
data.y = position.coords.longitude;
const json = JSON.stringify(data);
console.log(json);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function() {
const users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
alert(" added !");
} else {
console.table(users);
}
}
xhr.send(json);
}
// this will show an error to make it easier to debug
const error = e => console.log(e);
document.getElementById("go").addEventListener("click", evt => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ajouter, error);
}
});
<button id="go">Go</button>
First off, I would create a reusable post function, so you can use Objects that automatically convert to FormData. Perhaps this will help:
function post(url, send, func, responseType ='json', context = null){
const x = new XMLHttpRequest;
if(typeof send === 'object' && send && !(send instanceof Array)){
const c = context || x;
x.open('POST', url); x.responseType = responseType;
x.onload = ()=>{
if(func)func.call(c, x.response);
}
x.onerror = e=>{
if(func)func.call(c, {xhrErrorEvent:e});
}
let d;
if(send instanceof FormData){
d = send;
}
else{
let s;
d = new FormData;
for(let k in send){
s = send[k];
if(typeof s === 'object' && s)s = JSON.stringify(s);
d.append(k, s);
}
}
x.send(d);
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
function ajouter(){
navigator.geolocation.getCurrentPosition(position=>{
const pos = position.coords, data = {lat:pos.latitude, lng:pos.longitude, accuracy:pos.accuracy};
post('http://127.0.0.1:3000/reclamations', data, resp=>{
/* should echo json_encode($objOrAssocArray); in PHP - or send a JSON string back with node - resp will be JSON then - access like resp.property */
});
}, error=>{
throw new Error('error code:'+error.code+'; error message:'+error.message);
}, {enableHighAccuracy:true});
}

How to get geo data as a return from an ip on omegle?

Whenever I open a new Omegle video chat it returns me their IP when I run the code from the chrome console I was wondering how I can connect an API that automatically returns me the geo data along with the IP so I don't have to individually look it up.
window.oRTCPeerConnection = window.oRTCPeerConnection || window.RTCPeerConnection
window.RTCPeerConnection = function(...args) {
const pc = new window.oRTCPeerConnection(...args)
pc.oaddIceCandidate = pc.addIceCandidate
pc.addIceCandidate = function(iceCandidate, ...rest) {
const fields = iceCandidate.candidate.split(' ')
if (fields[7] === 'srflx') {
console.log('IP Address:', fields[4])
}
return pc.oaddIceCandidate(iceCandidate, ...rest)
}
return pc
}
This is probably what you are looking for:
window.oRTCPeerConnection = window.oRTCPeerConnection || window.RTCPeerConnection
window.RTCPeerConnection = function(...args) {
const pc = new window.oRTCPeerConnection(...args)
pc.oaddIceCandidate = pc.addIceCandidate
pc.addIceCandidate = function(iceCandidate, ...rest) {
const fields = iceCandidate.candidate.split(' ')
if (fields[7] === 'srflx') {
console.log('IP Address:', fields[4]);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
console.log(xmlHttp.responseText);
}
xmlHttp.open("GET", "https://ipinfo.io/" + fields[4] + "/json" , true); // true for asynchronous
xmlHttp.send(null);
}
return pc.oaddIceCandidate(iceCandidate, ...rest)
}
return pc
}
I included a GET for a JSON result that uses the field[4] IP from the script of the question. Works like a charm for me.
Try this API it returns a lot of geographic info about any IP, all you need to do is to give it the IP
http://extreme-ip-lookup.com/json/1.3.3.7
Just do a get request to this link and change 1.3.3.7 to any IP.
You can do a get request as following:
url = "http://extreme-ip-lookup.com/json/" + fields[4]
function httpGet(Url)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", Url, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
geographic_info = httpGet(url)
console.log(geographic_info)
Create a free account at https://ipinfo.io. You get 50,000 free requests per month. Then just parse the json like so:
const request = async () => {
const response = await fetch('https://ipinfo.io/' + StrangerIpGoesHere + '?
token=yourIpinfoTokenGoesHere');
const data = await response.json();
var strangerCity = data.city;
var strangerState = data.region;
var strangerCountry = data.country;
}

How to add Node.js result in my HTML project?

this is my project: http://cryptotipsitalia.sytes.net/.
I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price.
How can I add it?
That's my code:
function getValueBTC() { <!-- chiamata API --> /
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
var output;
console.log(url);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
var obj = JSON.parse(output);
var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */
document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.send();
}
let price = require('crypto-price');
price.getCryptoPrice('EUR', 'ETH').then(obj => {
console.log(obj.price); // It will print ETH rate per BTC
document.getElementById("cellaValoreETH").innerHTML = obj.price;
}).catch(err => {
console.log(err);
});
table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table>
Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work?
How can I add obj.price in my HTML code?
Thanks

Send data from Django to java script(in Chrome extension)

I have developed a chrome extension and I am inserting json data in mysql through django service. I want to send data from django to java script which is in chrome extension.
popup.js:
document.addEventListener('DOMContentLoaded', documentEvents, false);
function myAction(fname,femail,fpassword) {
var str = "name="+ fname.value + "&email=" + femail.value + "&password=" + fpassword.value;
var xmlhttp = new XMLHttpRequest();
alert(str);
var theUrl = "http://127.0.0.1:8000/polls/?";
xmlhttp.open("POST", theUrl, true);
xmlhttp.onreadystatechange = function() {
//alert(xmlhttp.readyState + " " + xmlhttp.status);
if (xmlhttp.readyState == 4){
alert("entered");
}
else{
alert("not entered");
}
};
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send(str);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
var theUrl = "http://127.0.0.1:8000/polls/?";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
}
};
xhttp.open("GET",theUrl,true);
xhttp.send();
}
function documentEvents() {
var submitButton = document.getElementById('submit')
submitButton.addEventListener('click',
function(event) {
var formId = document.getElementById('test');
var name = document.getElementById('name');
var email = document.getElementById('email');
var password = document.getElementById('password');
myAction(name,email,password);
});
}
views.py :
from django.http import HttpResponse
from django.http import HttpResponseRedirect, HttpResponse
from .models import UserProfile
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def index(request):
req = request.method
t = request.GET
print(req)
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
savedata = UserProfile(name=name,email=email,password=password)
savedata.save()
print('Hello %s %s %s' % (name, email, password))
return HttpResponse('successfully inserted')
My problem is how to send data from views and how to get that data in java script.Is there a way to define java script method name in django views. Please provide me the clear code of views and java script

Categories