This question already has answers here:
How do I post form data with fetch api?
(11 answers)
Fetch: POST JSON data
(17 answers)
Get the data received in a Flask request
(23 answers)
Closed 2 years ago.
I'm new using flask or JS, as that, I can't find a way to do what I want to.
I created a webserver using flask (in python) and it uses index.html as main page, I wanted to update data to the server every few secounds (maybe 1-3 secs). The thing is, I don't have any form to work with, or even queries and I don't know what else can I work with. The data I want to send is small string to be saved on server host later on.
<body>
<center>
<button onmousedown="sendDirectionKey('^')">^</button>
...
</center>
</body>
<script>
function sendDirectionKey(Key)
{
...
sendData(data_string);
}
function sendData(data)
{
...
}
</script>
An easy modern solution is the fetch() API:
function sendData(data)
{
const body = new FormData();
body.append("key", data);
return fetch("/receive", {method: "POST", body, credentials: "include"});
}
The equivalent receiver on the Python side would be something like
#app.route("/receive", methods=["POST"])
def receive():
print(request.form) # should have a `key` key
Related
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 2 years ago.
I am trying to build a small form in my website which will use ajax to save the form details to the database with php. I can do it with jquery, since I am a student, I don't want to use any external libraries.
I was able to use ajax "get method" and even manage to create a post method but I have no idea how to receive this data in the php script and process it.
This is the ajax code i used to send json data
subForm.addEventListener('click',()=>{
var forms = {
"name": document.getElementById('name').value,
"phone": document.getElementById('phone').value,
"email": document.getElementById('email').value,
"message": document.getElementById('message').value,
"exe" : true
}
var jString = JSON.stringify(forms);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "recieve.php");
xhttp.setRequestHeader("Content-Type" , "application/json")
xhttp.send(jString);
});
If you've managed to process a GET. You'll manage the POST just in the same way. By peeking in the global variable $_POST['myJson'] in your "recieve.php".
On the client side, you'd need then to stringify like so:
var jString = JSON.stringify({"myJson": forms});
Therefore, on the server side, $_POST['myJson'] will contain the object 'forms', which you constructed on the client side. And if you want to access let's say, the name property value, you do like so:
var nameValue = $_POST['myJson']['name'];
This question already has answers here:
How to save ArrayBuffer?
(3 answers)
How to post a file from a form with Axios
(9 answers)
Closed 4 years ago.
In my app, i'm uploading a file using FileReader and parsing it as an ArrayBuffer. The file properties are saved in an object, with structure like this:
file: {
name: 'fileName', // type string
content: ArrayBuffer // read like FileReader.readAsArrayBuffer(uploadedFile)
}
When I want to save the file to backend, I'm using axios, and sending a request like this:
axios({
url: "/api/v3/synchronous/commands",
method: "POST",
data: JSON.stringify(file),
headers,
})
The problem is that when it get's stringifed, content inside file becomes an empty object {}. How to go about this issue, without having to convert ArrayBuffer to something else, and then converting it back to ArrayBuffer?
This question already has answers here:
How to send secure AJAX requests with PHP and jQuery
(3 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I would like to send data from a Jquery script to a php page using POST.
My code is as follows:
$.ajax({
type: "POST",
url: 'http://mywebsite.com/add_data.php',
data: {value1: some_value,
value2: 123,
value3: ABC
},
My php script captures the data and records them in MySQL database.
$myvalue1 = $_POST['value1'];
$myvalue2 = $_POST['value2'];
$myvalue3 = $_POST['value3'];
The problem is that since JS code is visible in the source code, anyone can submit anything to my database...
Is there an easy way to make it more secure and prevent this from happening?
Any advice appreciated.
All data from the client always MUST be validated and sanitized, because all data from the client can be modificated/falsificated.
This question already has answers here:
Pass JavaScript variable to Flask url_for
(3 answers)
Closed 5 years ago.
$("#getVerification").click(function () {
var tmp=$("#cellphone").val();
console.log(tmp);
$.getJSON("{{ url_for('auth.sendsms', cellphone=tmp )}}",
function(data){
});
});
as the code above, I want to use the string variable tmp as a parameter in function url_for, but I can't figure out how,
Thanks A Lot!
You can't pass javascript variables to Jinja2 because of the way the template gets rendered.
Server side processing is done before client side.
Here is the order.
Jinja2 processes the template into proper markup.
The browser parses the markup into DOM and renders it.
The way this works only allows for passing Jinja2 variables to Javascript.
You need to do without using url_for Jinja2 directive and build your URL client side.
var tmp=$("#cellphone").val();
console.log(tmp);
$.getJSON(["<url_path for auth.send_sms>", tmp].join("/"),
function(data){
});
This question already has answers here:
jQuery posting JSON
(3 answers)
Submit a form using jQuery [closed]
(22 answers)
Closed 5 years ago.
I have read several postings on different examples for passing a javascript variable to flask through post/get forms. I still don't understand how to do this. From my understanding, the form creates a post/get that can then be called and received by the python flask script. Can someone write up a very simple example on what this should look like?
Starting from creating a variable with any value in javascript and then making the post/get. Lastly what should the receiving end on python should look like and finally print the variable from python.
How I did this was using an ajax request from the javascript which would look something like this. I think the easiest way would be using JQuery as well since it might be a bit more verbose with pure javascript.
// some movie data
var movies = {
'title': movie_title,
'release_date': movie_release_date
}
$.ajax({
url: Flask.url_for('my_function'),
type: 'POST',
data: JSON.stringify(movies), // converts js value to JSON string
})
.done(function(result){ // on success get the return object from server
console.log(result) // do whatever with it. In this case see it in console
})
Flask.url requires JSGlue which basically let's you use Flask's
url_for but with javascript. Look it up, easy install and usage. Otherwise I think you could just replace it with the url e.g '/function_url'
Then on the server side you might have something like this:
from flask import request, jsonify, render_template
import sys
#app.route("/function_route", methods=["GET", "POST"])
def my_function():
if request.method == "POST":
data = {} // empty dict to store data
data['title'] = request.json['title']
data['release_date'] = request.json['movie_release_date']
// do whatever you want with the data here e.g look up in database or something
// if you want to print to console
print(data, file=sys.stderr)
// then return something back to frontend on success
// this returns back received data and you should see it in browser console
// because of the console.log() in the script.
return jsonify(data)
else:
return render_template('the_page_i_was_on.html')
I think the main points are to look up ajax requests in jquery, flask's request.json() and jsonify() functions.
Edit: Corrected syntax