is it possible to reload a Django template after an ajax call?
This is my code.
script.js
$('.test').click(function(){
var platform = $('#testModal').attr('test-attr');
$.ajax(
{
type:"POST",
url:"test",
headers: {
'X-CSRFToken': TOKEN
},
dataType: "json",
cache : false,
processData : false,
contentType : false,
data: string,
success: function(data) {
location.reload();
}
});
});
view.py
return render(request, "user_interface/index.html", {'my_var': 'abc', 'my_var_2': 'cde'})
I tried to use return HttpResponse(json.dump({'res': 'Ok', 'err': None}), content_type = "application/json") but when i reload the page it fails.
Related
I am using Django and Ajax.
Im my view I have:
class MainView(View):
def get(self, request):
if not request.is_ajax():
return render(request, "main.html")
# hard coded both options for testing
return JsonResponse({"data": "xyz"}, status=400)
# return JsonResponse({"data": "xyz"}, status=200)
my ajax function looks like:
$("#start_calculation_button").click(function () {
$.ajax({
url: "/",
type: 'get',
data: {
...
},
success: function (response) {
console.log(response.data);
},
error: function (response) {
console.log(response.data);
}
})
})
But only the success function works? While the error part just gives back undefined
Any idea's why it is that way?
How can I fix it?
The parameters of success and error are different, in case of a success, these parameters are result, status, and xhr whereas for error, the parameters are xhr, status, and error. You thus should parse the xhr data with:
$("#start_calculation_button").click(function () {
$.ajax({
// ⋮
success: function (response) {
console.log(response.data);
},
error: function(xhr) {
var err = JSON.parse(xhr.responseText);
console.log(err.data);
}
})
})
I want to show the dropdown list with data response via Ajax call. Everything is working fine but I am getting this ValueError: Cannot use None as a query value error.
view:
def load_brand(request):
if request.is_ajax():
term = request.GET.get('term')
brand = Brand.objects.all().filter(brand__icontains=term)
return JsonResponse(list(brand.values()), safe=False)
ajax:
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {id: item.id, text: item.brand};
})
};
}
},
minimumInputLength: 1
});
In your ajax call you have not send the data i.e : which user type inside select2 and you are accessing them i.e : request.GET.get('term') which is empty so your .filter(brand__icontains=term) giving you error because term value is null.
Instead you can add below as well in your ajax call :
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
data: function(params) {
var query = {
term: params.term, //this will be paass
type: 'public' //optional..
}
// Query parameters will be ?term=[values]&type=public
return query;
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
id: item.id,
text: item.brand
};
})
};
}
},
minimumInputLength: 1
});
Also , at your server end you can check if the term has any value i.e :
if term:
brand = Brand.objects.all().filter(brand__icontains=term)
For more information check this
When i send data from ajax to view in Django I am getting none in data. What seems to be the problem. Here is mycode. Where as if i remove processData: false, contentType: false, then data is printed successfully but on file it gives error.
Ajax code
<script>
function submit_data()
{
var type = $('#type').val();
var subtype = $('#subtype').val();
var name = $('#name').val();
var price = $('#price').val();
var weight = $('#weight').val();
var details = $('#details').val();
var picture1 = $('#image1')[0].files[0];
var picture2 = $('#image2')[0].files[0];
var picture3 = $('#image3')[0].files[0];
var vedio_url = $('#vedio_link').val();
alert(picture1)
$.ajax({
url: '/add_record/',
type: 'POST',
headers: { "X-CSRFToken": '{{csrf_token}}' },
processData: false,
contentType: false,
data: {
type,
subtype,
name,
price,
weight,
details,
picture1,
picture2,
picture3,
vedio_url,
},
success: function (response) {
alert("datauploaded successfully!")
},
error: function(){
alert('error')
}
});
}
</script>
View code
def add_record(request):
print("Yes i am here")
type = request.POST.get('type')
subtype = request.POST.get('subtype')
name = request.POST.get('name')
price = request.POST.get('price')
weight = request.POST.get('weight')
details = request.POST.get('details')
picture1 = request.FILES.get('picture1')
picture2 = request.FILES.get('picture2')
picture3 = request.FILES.get('picture3')
vedi_url = request.POST.get('vedio_url')
print (picture1)
print(type)
print(request.POST)
return JsonResponse({'message':'success'},status=200)
Error:
Yes i am here
None
None
<QueryDict: {}>
its returning none, Why is that?
Ajax without files:
Your JS data element should be a dictionary, also remove processData and contentType parameters.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<input type="text" id="name"/>
<button type="button" id="send" onclick="submit_data()">Send<button/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function submit_data()
{
var name = $('#name').val();
$.ajax({
url: '/add_record/',
type: 'POST',
headers: { "X-CSRFToken": '{{csrf_token}}' },
data: {
'name': name,
},
success: function (response) {
alert(response.data)
},
error: function(){
alert('error')
}
});
}
</script>
</body>
</html>
views:
from django.shortcuts import render
from django.http import JsonResponse
def form_record(request):
return render(request, "mytemplate.html", {})
def add_record(request):
print("Yes i am here")
name = request.POST.get('name')
print(f"Post: {request.POST}")
return JsonResponse({'data': name},status=200)
Ajax with files:
Because you are sending binary data you should to use FormData:
function submit_data()
{
var name = $('#name').val();
var formData = new FormData() // changes here
formData.append('name', name) // and here
$.ajax({
url: '/add_record/',
type: 'POST',
headers: { "X-CSRFToken": '{{csrf_token}}' },
contentType: false, // and here
enctype: 'multipart/form-data', // and here
processData: false, // and here
cache: false,
data: formData, // <-- carefully here
success: function (response) {
alert(response.data)
},
error: function(){
alert('error')
}
});
}
Result:
you can do with a lot of entries please because I have a more complex problem.
in my case I have 6 entries when I enter an entry I have an output in the form of a table and at the end I have to make a final request which will take into account the rows that I have selected.
Excuse my English.
my js :
function submit_data(){
list_fournisseurs = selectcheck();
list_entrepot = selectcheck1();
var numdoc = $('#numdoc').val();
var reference = $('#reference').val();
var reference_doc = $('#reference_doc').val();
var date_debut = $('#date_debut').val();
var date_fin = $('#date_fin').val();
var format_fournisseur = new FormData();
var format_entrepot = new FormData();
var format_numdoc = new FormData();
var format_reference = new FormData();
var format_reference_doc = new FormData();
var format_date_debut = new FormData();
var format_date_fin = new FormData();
const format = [
format_fournisseur.append('list_fournisseurs', list_fournisseurs),
format_entrepot.append('list_entrepot', list_entrepot),
format_numdoc .append('numdoc', numdoc),
format_reference.append('reference', reference),
format_reference_doc.append('reference_doc', reference_doc),
format_date_debut.append('date_debut', date_debut),
format_date_fin.append('date_fin', date_fin),
]
$.ajax({
type : 'POST',
url : 'fournisseur_ajax',
data : {
'csrfmiddlewaretoken': csrf,
'format' : format,
},
//processData: false,
success : (res) =>{
console.log('res.data',res.data)
},
error : (err) =>{
console.log(err)
},
})
}
my view
if request.method == "POST" :
check_list_fournisseurs = request.POST.getlist("format_fournisseur[]")
print("########## voici la liste ###########",check_list_fournisseurs)
check_list_entrepot = request.POST.getlist("format_entrepot[]")
print("########## voici la liste ###########",check_list_entrepot)
print("numdoc ",num_doc)
print("item_ref",item_ref)
print("item_doc",item_doc)
print("date_depart", date_debut)
print("date_fin",date_fin)
context ={'check_list_entrepot':check_list_entrepot,"check_list_fournisseurs":check_list_fournisseurs, 'num_doc':num_doc, 'item_ref':item_ref, 'item_doc':item_doc, 'date_debut':date_debut, 'date_fin':date_fin}
return render(request,"final.html",context)
I am using quill editor to upload an image and the an ajax function is used to send the image to views.py.
This is the python function for uploading the image.
views.py
def upload_image(request):
if request.method == 'POST':
handle_uploaded_file(request.FILES.get('file'))
return HttpResponse("Successful")
return HttpResponse("Failed")
def handle_uploaded_file(file):
with open('upload/', 'wb+' ) as destination:
for chunk in file.chunk():
destination.write(chunk)
This is the ajax request:
function upload(file, callback) {
console.log('called');
var formData = new FormData();
formData.append('file', file);
$.ajax({
url : '{% url 'dashboard:upload_image' %} ',
type : 'POST',
data : formData,
contentType: 'multipart/form-data',
headers: { "X-CSRFToken": $.cookie("csrftoken") },
processData: false,
success: function(data) {
console.log('success');
callback(data.url)
}
});
}
Function calling upload() :
function(value) {
let fileInput = this.container.querySelector('input.ql-image[type=file]');
if (fileInput == null) {
fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/*');
fileInput.classList.add('ql-image');
fileInput.addEventListener('change', () => {
if (fileInput.files != null) {
upload();
}
});
this.container.appendChild(fileInput);
}
fileInput.click();
}
}
Error in string
with open('upload/', 'wb+' ) as destination:
Wrong path. Set the file name.
Getting a CSRF 403. The console.log statements below confirm that I'm grabbing the token. I'm submitting the request to the same domain on my local server.
internal.csrfToken = $.cookie('csrftoken');
internal.csrfSafeMethod = function(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
console.log("ajaxSetup");
console.log(internal.csrfToken);
if (!internal.csrfSafeMethod(settings.type)) {
console.log("Settings type");
xhr.setRequestHeader("X-CSRFToken", internal.csrftoken);
}
}
});
external.submitPayment = function (app_id, charge_now_amount, stripe_plan_id) {
// Submit a payment to the server and handle any errors.
$.ajax({
url: URLS.postPayment,
type: 'POST',
data: {
'app_id': STRIPE_CONFIG.app.id,
'amount': charge_now_amount,
'stripe_plan_id': stripe_plan_id
},
dataType: 'json',
success: function(response) {
alert("Success!");
},
error: function(jqXHR, textStatus, errorThrown ) {
alert("Error!");
}
});
};
not sure if this will help you. I had a similar problem. And fixed it by making a beforeSend functions that's add the X-CSRFToken
$.ajax({
url: url,
data: JSON.stringify({'name': value }),
type: 'POST',
dataType: 'json',
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
},
success: function(response) {
alert("Success!");
}
})