The following code allows you to submit forms and return a variation of the text from Flask using AJAX and JQuery:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('form.html')
#app.route('/process', methods=['POST'])
def process():
email = request.form['email']
name = request.form['name']
if name and email:
newName = name[::-1]
return jsonify({'name' : newName})
return jsonify({'error' : 'Missing data!'})
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
<br><br><br><br>
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="emailInput">Email address</label>
<input type="email" class="form-control" id="emailInput" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="nameInput">Name</label>
<input type="text" class="form-control" id="nameInput" placeholder="First Name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<br>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
name : $('#nameInput').val(),
email : $('#emailInput').val()
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.name).show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});
But when I slightly modify the code to do the same thing with a uploaded file's name it doesn't work. All I have done is changed the type of form so that it takes in files and then made it so that it reverses the filename rather than the inputted text from the previous version. Do you know what I am doing wrong here?
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('form.html')
#app.route('/process', methods=['POST'])
def process():
filename = request.files['file'].filename
if filename:
newName = filename[::-1]
return jsonify({'name' : newName})
return jsonify({'error' : 'Missing data!'})
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
<br><br><br><br>
<form method="POST" action='/process' enctype="multipart/form-data">
<div>
<label for="file">Choose file to upload</label>
<input type="file" id="file" name="file">
</div>
<div>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
<br>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
file : $('#file')
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.name).show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});
If you use an object of the type FormData to serialize and transfer the data of the form it should work.
$(document).ready(function() {
$('form').submit(function(event) {
let formData = new FormData(event.target);
$.ajax({
data: formData,
type : 'POST',
url : '/process',
contentType: false,
processData: false
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
} else {
$('#successAlert').text(data.name).show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});
Related
I have a HTML control panel with various buttons and sliders. All of the buttons are operational and when clicked send a post request which my Python app receives and then executes functions.
I cannot seem to get the slider controls to work, When I adjust the slider I get the following error:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'button'
This is promising as at least I can see it trying to do something and failing, which is the best result achieved thus far. My javascript and AJAX knowledge is limited and I need a solution for the slider to POST request on any onchange value that python can then interpret.
I initially had the following HTML:
<input id="slider" type="range" min="0" max="100" value="50" onchange="updateVolume(getElementById('slider').value); return false;">
Javascript:
<script>
function updateVolume (vol) {
$.ajax({
method: "POST",
url: '{{ url_for('main.control_panel', video_id=video.id) }}',
data: { volume: vol}
})
.done(function( msg ) {
// optional callback stuff if needed
// alert( "Data Saved: " + msg );
});
}
</script>
This threw up the same error.
This is my current code that also throws the same error:
HTML:
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
Javascript:
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.ajax({
url: '{{ url_for('main.control_panel', video_id=video.id) }}',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
Python:
#main.route("/control_panel/<int:video_id>", methods=['GET', 'POST'])
def control_panel(video_id):
video = video.query.get_or_404(video_id)
if request.method == 'POST':
... #IF ELIF for various button functions here
volume = request.form['slider']
return json.dumps({'volume': volume})
return render_template('/control_panel.html', title=video.video, video=video)
Any support would be greatly appreciated as I'm struggling to find solutions on the web along with me aforementioned js/ajax knowledge.
Thanks
EDIT:
This is a recreation of the problem:
python:
from flask import Flask, request, redirect, url_for, render_template, json
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def control_panel():
if request.method == 'POST':
if request.form['button'] == 'button-play':
print("play button pressed")
elif request.form['button'] == 'button-exit':
print("exit button pressed")
elif request.form['slider']:
volume = request.form['slider']
return json.dumps({'volume': volume})
print(volume)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
HTML:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Slider</title>
</head>
<body>
<div class="container" id="control_panel_1">
<form action="/" method ="post" enctype="multipart/form-data" id="form">
<div class="row">
<div class="col">
<button class="btn btn-primary" button type="submit" name="button" value="button-play">PLAY</button>
<button class="btn btn-primary" button type="submit" name="button" value="button-exit">EXIT</button>
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
</div>
</div>
</form>
<!--- SCRIPTS --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
<script>
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.ajax({
url: '/index.html',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
</script>
</html>
Problem is because $('form').serialize() sends only values from <input> but not from <button> but in Flask you check request.form['button'] and it raises error because key button doesn't exists in dictionary request.form.
You have to use
request.form.get('button')
and then it returns None when button doesn't exists in dictionary
BTW:
you have only #app.route("/", ...) so AJAX has to send to /, not to
/index.html
using print(volume) after return ... is useless becuse return ends function
in Flask you can use return jsonify(dict) instead of return json.dumps(dict) and then it sends special headers and JavaScript converts it to object and you can get response.volume. Using json.dumps(dict) it sends it as html/text and you would have to use JSON.parse(response).volume
Working code in one file (using template_render_string instead of template_render) so everyone can easily test it.
from flask import Flask, request, redirect, url_for, render_template, json, render_template_string, jsonify
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def control_panel():
print('request.form:', request.form)
if request.method == 'POST':
if request.form.get('button') == 'button-play':
print("play button pressed")
elif request.form.get('button') == 'button-exit':
print("exit button pressed")
elif request.form.get('slide'):
volume = request.form.get('slide')
print('volume:', volume)
#return jsonify({'volume': volume})
return json.dumps({'volume': volume})
print('render')
return render_template_string('''<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Slider</title>
</head>
<body>
<div class="container" id="control_panel_1">
<form action="/" method ="post" enctype="multipart/form-data" id="form">
<div class="row">
<div class="col">
<button class="btn btn-primary" button type="submit" name="button" value="button-play">PLAY</button>
<button class="btn btn-primary" button type="submit" name="button" value="button-exit">EXIT</button>
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
</div>
</div>
</form>
<!--- SCRIPTS --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
<script>
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.post({
url: '/',
data: $('form').serialize(),
success: function(response){
alert(response);
alert(response.volume); // works with jsonify()
alert(JSON.parse(response).volume); // works with json.dumps()
console.log(response);
},
error: function(error){
alert(response);
console.log(error);
}
});
}
</script>
</html>''')
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)
hey im trying to upload an image/video via the link (https://i.picsum.photos/id/237/536/354.jpg) of the image to my mongodb,
i used to work with choose file option , but now i want to change the process to be made by image or video url,
i have tried to change the choose file to text input , but its not working , how can i solve this problem
didnt found any information about uploading by link only for choose file .
this is the route and the storage structure:
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// #route POST /upload
// #desc Uploads file to DB
app.post('/upload', upload.single('file'), (req, res) => {
// res.json({ file: req.file });
res.redirect('/');
});
this is the view i made:
the choose file is commnted out
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<style>
img {
width: 100%;
}
</style>
<title>Mongo File Uploads</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
<h1 class="text-center display-4 my-4">Mongo File Uploads</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="text" name="file" id="file" >
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
<% if(files){ %>
<% files.forEach(function(file) { %>
<div class="card card-body mb-3">
<% if(file.isImage) { %>
<img src="image/<%= file.filename %>" alt="">
<% } else { %>
<%= file.filename %>
<% } %>
<form method="POST" action="/files/<%= file._id %>?_method=DELETE">
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
<% }) %>
<% } else { %>
<p>No files to show</p>
<% } %>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
thanks advice to all the helpers !
i want to send to input text (url of image) and then upload it to mongodb using multer ,
it possible to do it without downloading the image ?
im using multer and multer-gridfs-storage
i sucsuus only with choose input type of file , that i must to select from my pc , but i want to pass an image url and upload it to the mongodb using multer-gridfs-storage , that is possible ?
this is the request
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// #route POST /upload
// #desc Uploads file to DB
app.post('/upload', upload.single('file'), (req, res) => {
// res.json({ file: req.file });
res.redirect('/');
});
this is the view
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<style>
img {
width: 100%;
}
</style>
<title>Mongo File Uploads</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
<h1 class="text-center display-4 my-4">Mongo File Uploads</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="text" name="file" id="file" >
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
<% if(files){ %>
<% files.forEach(function(file) { %>
<div class="card card-body mb-3">
<% if(file.isImage) { %>
<img src="image/<%= file.filename %>" alt="">
<% } else { %>
<%= file.filename %>
<% } %>
<form method="POST" action="/files/<%= file._id %>?_method=DELETE">
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
<% }) %>
<% } else { %>
<p>No files to show</p>
<% } %>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>
I'm trying to delete a list of images selected via checkbox via Ajax, which have been uploaded via Django Ajax Uploader. I've successfully obtained a list of the images but I'm not sure how to pass it Django function via Ajax. Can anyone please advise on:
How can I pass the list of selected images to a Django function to delete the images?
How should I handle the CSRF for the ajax portion?
html
<!DOCTYPE html>{% load static from staticfiles %} {% load i18n %}
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Demo</title>
<script src="{% static 'js/jquery.min.js' %}"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<style>
input.chk {
margin-left: 70px;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="content" class="clearfix container">
{% load i18n crispy_forms_tags %}
<form method="post" action="." enctype="multipart/form-data">
{% csrf_token %} {% crispy form %} {% crispy formset formset.form.helper %}
<div class="image-upload-widget">
<div class="preview">
</div>
<div class="file-uploader">
<noscript>
<p>{% trans "Please enable JavaScript to use file uploader." %}</p>
</noscript>
</div>
<p class="help_text" class="help-block">
{% trans "Available file formats are JPG, GIF and PNG." %}
</p>
<div class="messages"></div>
</div>
<input type="submit" name="save" class="btn btn-primary pull-right" value="Submit">
<input type="button" id="delete" class="btn btn-primary pull-left" value="Delete Selected Files">
</form>
</div>
</div>
<script src="{% static 'js/fileuploader.js' %}"></script>
<link href="{% static 'css/fileuploader.css' %}" media="screen" rel="stylesheet" type="text/css" />
<script>
$(function() {
var uploader = new qq.FileUploader({
action: "{% url 'planner:ajax_uploader' %}",
element: $('.file-uploader')[0],
multiple: true,
onComplete: function(id, fileName, responseJSON) {
if (responseJSON.success) {
url = '<label for="' + fileName + '"><img src="' + {{MEDIA_URL}} + responseJSON.url + '" alt="" /></label>';
checkbox = '<p><input type="checkbox" class="chk" id="' + fileName + '" name="' + fileName + '" value="0" /></p>';
$('.preview').append(url);
$('.preview').append(checkbox);
} else {
alert("upload failed!");
}
},
onAllComplete: function(uploads) {
// uploads is an array of maps
// the maps look like this: {file: FileObject, response: JSONServerResponse}
alert("All complete!");
alert(checkbox);
},
params: {
'csrf_token': '{{ csrf_token }}',
'csrf_name': 'csrfmiddlewaretoken',
'csrf_xname': 'X-CSRFToken',
},
});
});
</script>
<script>
$("#delete").on('click', function() {
var allVals = [];
$(":checkbox").each(function() {
var ischecked = $(this).is(":checked");
if (ischecked) {
allVals.push(this.id);
}
});
});
</script>
</body>
</html>
Once you got the list of images to delete, you pass it on to an Ajax call that will be handled by a Django view, like so:
function submitData(data) {
var csrftoken = getCookie('csrftoken'); // from https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax
$.ajax({
type: 'POST',
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
data: JSON.stringify(data),
url: {% url 'image_handler' %}
}).done(function(data) {
console.log(data.deleted + ' images were deleted');
}).error(function(data) {
console.log('errors happened: ' + data);
});
}
Then, in your views.py:
def image_handler(request):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
str_body = request.body.decode('utf-8')
changes = json.loads(str_body)
for change in changes:
pass # `change` contains the id of the image to delete
data = {'status': 200,
'deleted': len(changes)}
return JsonResponse(data)
It works pretty nicely :)