I am trying to send this toDataURL image to the server through AJAX. Unfortunately, every time it sends - no matter how I finagle it - I can only get either a 403 Forbidden error, a javascript error, or - at best - an empty dictionary item, while the other fields are accurate. Any ideas?
javascript
function SaveImage(n){
var imageFile = document.getElementById("img-file"+n);
// Set that you want to download the image when link is clicked
imageFile.setAttribute('download', 'image.png');
// Reference the image in canvas for download
imageFile.setAttribute('href', canvas.toDataURL());
addMeme(imageFile);
}
function addMeme(n){
var f= n;
var patch = '{% url "testing" %}';
var post_data = {
'csrfmiddlewaretoken':"{{ csrf_token }}",
imageBase64:f,
g: 'jjj',
};
$.ajax({
type: "POST",
url: patch,
data:post_data,
dataType: 'json',
success: function(data){
}
});}
views.py
def testing(request):
if request.method == 'POST':
response_json = request.POST
response_json = json.dumps(response_json)
data = json.loads(response_json)
print(data['imageBase64'])
return JsonResponse(data, safe=False)
Related
I have a canvas where I draw a rectangle and save their coordinates.
The coordinates are saved in a Javascript dictionary.
Using the following script, I can save / download a file with the dictionary in it.
But it gets saved only in the Downloads folder.
function myFunction() {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURI(JSON.stringify(dict));
hiddenElement.target = '_blank';
hiddenElement.download = 'dict.json';
hiddenElement.click();
}
I want to save it on Django's media folder per user.
media > {{user}} > dict.json
Any help highly appreciated.
Solved it using Ajax.
Ajax script:
$(document).ready(function() {
$("#mybutton").click(function() {
$.ajax({
url: "{% url 'drawing' user %}",
type: "POST",
dataType: "json",
data: {
url: JSON.stringify(dict), // coordinates are saved on dict
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
alert("Drawing saved!");
},
error : function(xhr, errmsg, err) {
alert("Drawing could not be saved!");
}
});
});
});
views.py:
def drawing(request):
user = request.user
url = request.POST.get('url') # url from ajax will be saved here.
first_value = next(iter(((request.POST).dict()).values())) # cleaning output
with open("media/{}/dict.json".format(user), 'w') as draw:
draw.write(first_value) # save to file
return JsonResponse(url, safe=False)
I am currently working on the below flask code. I'm trying to redirect to another HTML page using render_template but it's not working. However, I have tried to send back the JSON response to the AJAX at the client-side and by using the AJAX success response at the Client JavaScript code and by using the window.location.href functionality I am giving the URL of that HTML it's working.
But I need to use the render_template to redirect to another URL which actually fulfills my requirement. Please help me out.
function myFunction() {
$.ajax({
url: '/ValidateOTP',
type: 'POST',
data: JSON.stringify($('#OTP').val()),
contentType: 'application/json;charset=UTF-8',
success: function(response) {
jsonvariable = response['success'].toString();
if (jsonvariable == 'true')
window.location.href = 'http://localhost:63342/ElectricMan/templates/electricprofwelcomepage.html';
else if (jsonvariable == 'false')
document.getElementById("div2").innerHTML = "OTP didn't match !! Please click the GET OTP button to re-generate OTP";
document.getElementById("div2").style.color = "Red";
},
error: function(response) {
alert(response)
}
});
};
#app.route('/ValidateOTP', methods=['GET','POST'])
def ValidateOTP():
OTP = request.get_json()
otpinstant=session['OTPINSTA']
if otpinstant==OTP:
Session = sessionmaker(bind=engine)
s = Session()
query = s.query(ElectricMan).filter_by(email_id=email).first()
result=query.first_name
if result:
session['logged_in'] = True
#return render_template('electricprofwelcomepage.html')
resp = jsonify(success=True)
return resp
else:
resp = jsonify(success=False)
return resp
I'm creating an app to calculate a projection of the transit given the years and some other values, first I created a script in javascript where depending on if the user decide to add a new type of vehicle a new div is created with unique ids and names and ofcourse the data the user introduced, for showing the final result i'm using ajax, the problem comes when i tried to access the data via flask, i'm getting a bad request from the names of each vehicle like if they did not exist, but the page is actually displaying them (hope you understand my english and my problem :) )
I've tried giving a specific name (a1) an then tried to take the value in flask but i still can#t make it work.
Python
#app.route("/pavimentos/calculoTransito" , methods=['POST'])
def calculoTransito():
direc = float(request.form["direc"])
zr = float(request.form["zr"])
years = float(request.form["years"])
tc = float(request.form["direc"])
vehicles = int(request.form["vehicles"])
car1 = request.form.get("a1", None)
if car1==None:
print("No funciona")
else:
print("Funciona")
always get "No funciona"
Javascript
countClicks = 0
lista_vehiculos = []
function addVehicle(){
countClicks += 1;
//var automovil = document.getElementById("automovil").value
var fd = document.getElementById("damage_factor").value
var currentType = document.getElementById("vehicleType")
if(currentType.value == 1){
var icon = "<h2 class='pt-4'><i class='fas fa-car text-secondary'></i></h2>";
var tipoVehiculo = "Automóvil";
}
... More code for select the currentType ...
var vehicleStyle = "<div><input id=a" + countClicks + "name=a" + countClicks + "value=" + fd + "></div>"
lista_vehiculos.push(vehicleStyle)
var vehicle = document.getElementById("vehiclesContainer").innerHTML += lista_vehiculos[countClicks-1]
document.getElementById("vehicles").value = countClicks
}
AJAX part
$(document).ready(function(){
$('form').on('submit', function(event){
$.ajax({
data:{
direc: $('#direc').val(),
zr: $('#zr').val(),
years: $('#years').val(),
tc: $('#growingRate').val(),
vehicles: $('#vehicles').val(),
car1: $('#a1').val()
},
type: 'POST',
url: '/pavimentos/calculoTransito'
})
.done(function(data){
if (data.resultado){
$('#resultado').text(data.resultado).show()
}
})
event.preventDefault();
});
});
You're not submitting a form, you're sending JSON. The initial event might be the submission of a form, but your AJAX uses event.preventDefault() and does not end up submitting a traditional serialized form. You can't use car1 = request.form.get("a1", None) here.
Firstly, you should correct your AJAX to add a contentType:
$(document).ready(function(){
$('form').on('submit', function(event){
$.ajax({
data: JSON.stringify({
direc: $('#direc').val(),
zr: $('#zr').val(),
years: $('#years').val(),
tc: $('#growingRate').val(),
vehicles: $('#vehicles').val(),
car1: $('#a1').val()
}),
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/pavimentos/calculoTransito'
})
.done(function(data){
if (data.resultado){
$('#resultado').text(data.resultado).show()
}
})
event.preventDefault();
});
});
And then you need to change your Flask method from request.form to request.json. So the Flask side would look something like:
#app.route("/pavimentos/calculoTransito" , methods=['POST'])
def calculoTransito():
req = request.json
direc = float(req["direc"])
zr = float(req["zr"])
...
car1 = req.get("a1", None)
if car1 is None: # None is a singleton, you shouldn't use == here
print("No funciona")
else:
print("Funciona")
LATE EDIT
This can't work because calculoTransito does not actually return anything, so Flask will throw an error from that alone. Your view function actually has to return something other than an implicit None.
I am creating simple "rock paper scissors" game with some css animations and so on, where most of the stuff happens in javascript, as learning JS is what I am focusing on mostly at the moment.
User vs computer match also happens in javascript. When match is finished I am assigning users earned exp(points) to new variable.
What I am trying to do now is sending that data (earned exp) to the views, so I can save it back in a database (users.exp).
I think jQuery ajax or fetch api should do that if I am right but after hours of trying I probably just don't get it.
Any1 can give me some tips, explanation? Not just solution please.
Views:
#login_required
def profile(request):
if request.user.is_authenticated:
user = request.user
userObj = Profile.objects.filter(user=user)
usersLevel = userObj[0].level
usersPoints = userObj[0].points
context = {
'usersLevel': usersLevel,
'usersPoints': usersPoints,
}
return render(request, 'rps_app/game.html', context)
else:
print('No user logged in!')
return render(request, 'rps_app/game.html')
This is my template where Iam loading users data:
<script type="text/javascript">
var usersLevel = '{{usersLevel|safe}}';
var usersPoints = '{{usersPoints|safe}}';
</script>
js:
let users_level = Number(usersLevel);
let users_points = Number(usersPoints);
progressbar.style.width = `${users_points}%`;
...
javascript:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/game',
csrfmiddlewaretoken: "{{ csrf_token }}",
type: 'get',
success: function(data) {
console.log(data);
alert(data);
},
failure: function(data) {
alert('Your code is crap mate');
}
});
});
})
************ . E D I T E D . ***********
Thats what I got now:
js:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/test/earned_exp=100/',
csrfmiddlewaretoken: "{{ csrf_token }}",
success: function(data) {
alert('succes');
},
failure: function(data) {
alert('Your code is crap mate');
}}); });})
views:
def pass_variable(request, earned_exp=None):
some_variable = request.GET.get('earned_exp')
console.log(some_variable)
return HttpResponse('<h1>ok.{}</h1>'.format(earned_exp))
url:
path('test/<earned_exp>/', user_views.pass_variable, name='pass_variable'),
You can pass variables as URL parameters and get them through the request object.
$.ajax({
url: 'mycoolwebsite.com/path/?earned_xp=100'
success: function(e){
alert("success");
},
error: function(e){
alert("error")
}
});
class MyView(View):
def get(self, request):
xp = request.GET.get("earned_xp")
# do whatever you want with the XP now.
In case you want to send multiple URL parameters, you can seperate them by & here's an example url
https://example.com/?hello=world&goodbye=coding
The thing is that i have an embedded python interpreter and after a user presses "Run", the output from interpreter gets transferred to a pre element. I want to take that data from pre element and send it to django server through AJAX. The problem is that even after assigning of that data to a variable, django gets nothing. Also i can start interpreter and AJAX script only after pressing "Run", both work work with onclick. I am using POST request.
`$(document).ready(function(){
$('#run').click(function(){
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
$.ajax({
url: '/courses/python3/lesson_validate/{{ lesson_number }}/',
data: {"text": input_string, csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: "json",
type:"POST",
success: function(data, textStatus){
alert('get_response');
alert(data);
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
});
});
`
So that code works perfectly
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
but when i try to use that variable in ajax, server fails to get it.
I tried using async: false, it doesn't change anything.
This is view code:
`def lesson_validate(request,lesson_number):
args = {}
args.update(csrf(request))
out_compare = Lessons.objects.get(id=lesson_number).lesson_output
if request.method == "POST" and request.POST.get('text') == out_compare:
text = "they are equal"
return HttpResponse(json.dumps(text), content_type='application/javascript')
else:
args['testtest']=request.POST.get('text')
return render_to_response('course_lesson.html', args, context_instance=RequestContext(request))`
After i check request.POST.get('text') it is empty
The question is how can i get data from ajax, from a variable assigned before, not just from a sting?
It looks like you're sending JSON to the server in that request, so to get the variables in Django you'd need to do:
def lesson_validate(request,lesson_number):
import json
data = json.loads(request.body)
text = data.get('text')
# Do stuff.