send images with ajax and django - python

I try to send images from <input type="file" id="file" name="file" accept="image/*" multiple> without sending al the form. I found many post which explain this so I do this
urls.py
url(r'^images/', 'app.views.images', name='images'),
view.py
def images(request):
if request.method == 'POST':
print('hello')
jquery
$("#file").change(function (){
try{
var formdata = new FormData();
var files = $('#file')[0].files;
formdata.append('file',files);
jQuery.ajax({
url: "images/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
}
catch(err){
alert(err.message);
}
});
But this gives me "POST /images/ HTTP/1.1" 403 error
I did diferent test and I think the error is the data: formdata part

You need to either send the csrf_token in the ajax request.
formdata["csrfmiddlewaretoken"] = '{{ csrf_token }}'; //add csrf token to the reauest data
jQuery.ajax({
url: "images/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
Or use #csrf_exempt on the your view.
#views.py
#csrf_exempt
def images(request):
if request.method == 'POST':
print('hello')

Related

How to send data to the view in Flask using AJAX?

Please help...
I am trying to upload a csv or excel file, and using an Ajax call trying to send it to Flask along with an integer.
HTML Form:
<form id="testFileForm" method="POST" action="{{ url_for('auto') }}" enctype="multipart/form-data">
{{ fileUploadForm.csrf_token }}
<label class="connect choosefile setInput config-button-size " >
<i class="fa fa-file" aria-hidden="true"></i>
<span id="testFileLabel">Choose Test Data</span>
{{ fileUploadForm.file(class="input1 btn btn-primary", id="testFile") }}
</label>
<label class="form-label" style="padding-left:10px ;">
<input class="btn btn-primary config-button-size" id="testFilebtn" type="submit" value="Process">
</label>
</form>
Ajax Call:
$('#testFilebtn').click(function() {
var file = document.getElementById("testFile").files[0];
alert(file)
var data = {
file: file,
id : 1
}
alert('file loaded')
$.ajax({
data: data,
type: "POST",
url: "auto",
"Content-Type": 'application/json',
dataType: 'json',
success: function(response) {
alert(response)
},
});
});
View:
#app.route('/auto', methods=['POST', 'GET'])
#login_required
def auto(dataset_id=None):
fileUploadForm = FileUploadForm()
if request.method=='POST' and fileUploadForm.validate_on_submit():
try:
file = request.files['file']
id = request.form['id']
print('id')
print(id)
except UploadNotAllowed:
return redirect(url_for("auto"))
# return redirect(url_for("auto"))
return "te"
I get error while retrieving the id, which indicates I am also not receiving file from ajax call.
Error:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'id'
I am new to Ajax calls, some help would highly be appreciated...
I believe you could do it like this :
var fd = new FormData($('#testFileForm')[0]);
fd.append( 'id', 1 );
$.ajax({
url: 'http://example.com/',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Notes:
Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string.
See the docs for more info.
Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

Django - template reloads after ajax response

I'm sort of new with Django and I ran through an issue. I'm sending a post request to django view and return the function back with HttpResponse in order to change my template's div contents to the passed value from my view. The issue is: once ajax responds and changes it's div's value; the page instantly reloads. Do you guys have any idea why?
Views.py
def index(request):
if request.is_ajax():
print("request is ajax")
details = request.POST.get('id')
return HttpResponse(details)
else:
return HttpResponse("Failed)
base.html
<button id="checkres">Check result</button>
<form name="testform" id="testform" method="post">
{% csrf_token %}
<input type="text" id="rowfield">
<input type="submit">
</form>
$("#testform").submit(function (event){
$row_num = $('#rowfield').val()
$("#responseresult").text('checking');
$.ajax({
type: "POST",
url: "/bot",
data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
success: function(data){
$("#responseresult").text(data);
alert(data);
}
});
});
Your javascript submit event not calling event.preventDefault(), that's the reason that after ajax response, the is refreshing. Change your javascript function to:
$("#testform").submit(function (event){
$row_num = $('#rowfield').val()
$("#responseresult").text('checking');
$.ajax({
type: "POST",
url: "/bot",
data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
success: function(data){
$("#responseresult").text(data);
alert(data);
}
});
event.preventDefault(); // prevents the page from refreshing.
});
Further read about preventDefault()
Try this for your view
def index(request):
if request.is_ajax():
print("request is ajax")
details = request.POST.get('id')
return JsonResponse(details, safe=False)
else:
return JsonResponse("Failed" safe=False)
You need to prevent submit as well.
$("#testform").submit(function (event){
$row_num = $('#rowfield').val()
$("#responseresult").text('checking');
$.ajax({
type: "POST",
url: "/bot",
data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
success: function(data){
$("#responseresult").text(data);
alert(data);
}
});
event.preventDefault(); // prevents the page from refreshing.
});

How to populate a django form in a POST request with data from an ajax call?

I'm sending form data via an ajax call after user hits submit button and then handling this request in my views, but the form is empty. How can I populate the form?
This is my code:
My JS file:
var csrftoken = getCookie('csrftoken'); //getCookie is a csrf_token generator
var form = $(this).closest('form')
$.ajax({
url: form.attr("action"),
data: { // if I change this line to data: form.serialize(), it works fine!
csrfmiddlewaretoken : csrftoken,
form: form.serialize(),
},
type: form.attr("method"),
dataType: 'json',
success: function (data)
{
//Do a bunch of stuff here
}
})
My views:
def task_edit(request, pk):
task = get_object_or_404(Task, pk=pk)
if request.method == 'POST':
task_form = NewTaskForm(request.POST) # This is empty!
else:
task_form = NewTaskForm(instance=task) # This for populating the edit modal, works fine!
I'm not doing the data: form.serialize() because I need to send additional data with the ajax request. How do I get this working?
You can write as below:-
$form_data = $("#idofform").serialize();
And then in ajax
data : $form_data+'&key=value',
You can use services like https://www.formkeep.com to capture form data using AJAX.
This may be a good idea if you are already using a JavaScript framework, you want to add validation logic, or you don't want to redirect the user after they submit the form.
You can submit to FormKeep using a standard AJAX request. To ensure the request does not cause a redirect, be sure to set the Accept header to application/javascript.
Given the following form:
<form id="newsletter-signup" action="http://formkeep.com/f/exampletoken" method="POST" accept-charset="UTF-8">
<input type="hidden" name="utf8" value="✓">
<input name="email" type="email">
<input value="Submit" type="submit">
</form>
Here's an example of how to submit a form with jQuery:
$(function() {
$('#newsletter-signup').submit(function(event) {
event.preventDefault();
var formEl = $(this);
var submitButton = $('input[type=submit]', formEl);
$.ajax({
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
data: formEl.serialize(),
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
});
});
});
That's it. Once your data is securely captured in FormKeep you can easily store it, manage it or connect it with 1000s of other systems like Google Docs and Hubspot and Mailchimp.

Flask: POST request using AJAX

I want to make a post request by using ajax. I want to use the input value as function parameter and append the function return into a html table. I don't know but a think that my code is wrong and the ajax is not working.
Note: For testing, I'm taking input value and returning to html page.
network.html
<script type="text/javascript">
$(function(){
$('#button').click(function(){
var dados = $('#search-input').val();
$.ajax({
url: '/network',
data: $('form').serialize(),
type: 'POST',
success: function(data){
$('#result').append(data)
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
});
</script>
<form name='form' method="POST">
<input type="text" name="search-input" id="search-input" class="form-control" placeholder="Users and ID" >
<button type="submit" class="btn btn-primary" id="button">Search</button>
</form>
<span id=result>{% print dado %}</span>
app.py
#app.route('/network',methods=['POST','GET'])
def network():
if request.method == 'POST':
input = request.form['search-input']
return render_template('network.html',dado=input)
else:
return render_template('network.html',dado='')
Edit: After this update what's returning is a JSON format
{
"dado": "INPUT VALUE"
}
app.py
#app.route('/network',methods=['POST','GET'])
def network():
if request.method == 'POST':
input = request.form['search-input']
return jsonify(dado=input)
else:
return render_template('network.html',dado='')
network.html
<script type="text/javascript">
$(function(){
$('#botao').click(function(){
var dados = $('#search-input').val();
$.ajax({
url: "{{ url_for('network') }}",
data: JSON.stringify(dados),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(data){
$('#result').append(data["dado"])
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
});
</script>
You got to return JSON!
Instead of return render_template(...), use:
return jsonify(dado = input)
Then in your ajax success call:
success: function(data){
$('#result').append(data["dado"])
console.log(data);
}
...
}); // end AJAX
e.preventDefault();
Don't forget to import jsonify
from flask import jsonify

Flask Ajax returns POST HTTP/1.1" 400 error while uploading

Hi all I have a simple form with an upload button like this.
<form role="form" id="sf" name = "sf" method="post"
enctype="multipart/form-data" action="javascript:void();">
<input type="file" id="file" name="file" class="file">
</form>
my js looks like this.
$('#file').bind('change', function() {
var form_data = new FormData($('#suject-form')[15]);
var request = $.ajax({
url: "/upload",
type: "POST",
contentType: "application/json",
cache: false,
processData: false,
async: false,
data: {
file: new FormData($('#suject-form')[0]),
state: 'testing'
},
dataType: "json",
})
.done(function(data){
console.log(data);
})
return false;
});
-
When I try to get the file data it keeps giving me the 400 error,
-
#app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
state= request.form['state']
files = request.files['file']
# if I leave out file it returns but fails when leave in files
return jsonify(result=[state])
Anyone know what I'm doing wrong? thanks!

Categories

Resources