Change URL and content without refreshing django - javascript

I am fetching a json response from my django response by this url /inbox/<str:username> to get a json response of all the messages in the conversation with that user.
The problem starts with the inbox page which holds the threads and chatbox on the same page like instagram which looks like this
but as it can be seen that I want the url to be like with the username. Let's say when I click on thread with dummy I want the url to be like "inbox/dummy" but in this my url is "/inbox" which will not let me initiate the socket for messaging, my views.py that renders this inbox template is
views for inbox
thread_objs= Thread.objects.by_user(user=request.user)
l=len(thread_objs)
chat_objs=[]
for i in range(l):
chat_objs.append(list(thread_objs[i].chatmessage_set.all()).pop())
chat_objs_serialized=[]
for i in range(l):
chat_objs_serialized.append(json.dumps(ChatMessageSerializer(chat_objs[i]).data))
for i in range(l):
print(chat_objs_serialized[i])
thread_objs_list=[]
for i in range(l):
thread_objs_list.append(json.dumps(ThreadSerializer(thread_objs[i]).data))
return render(request,'uno_startup/inbox.html',context={"Threads":thread_objs_list,"Messages":chat_objs_serialized})
now when I click a thread it's content should load on the right side of screen as with the javascript of inbox.html that is this page in this image.
javascript of inbox
<body>
<div class='container'>
<div class='row'>
<div class="col-md-4" id ="Threadholder">
<ul id ="Threadbox">
{% for object in threads %}
<li>{% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif %}</li>
{% endfor %}
</ul>
</div>
<div class="col-md-8" id="Chatholder" >
<ul id="Chatbox">
</ul>
<form id="form" method="POST">
<input type="hidden" value="{{ user.username }}" id="myusername">
<input type="text" id="chat_message">
<input type="submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
<script>
var threads={{ Threads|safe }};
var messages={{ Messages|safe }};
const l=threads.length
const threadholder=$("#Threadbox")
for(i=0;i<l;i++){
var data=JSON.parse(threads[i])
var Message=JSON.parse(messages[i])
var username =data.second.username
if (username=="{{ user.username }}"){
username=data.first.username
}
var thread=document.createElement("li")
var main=document.createElement("a")
var div=document.createElement("div")
var username_holder=document.createElement("p")
div.className="thread"
var p=document.createElement("p")
p.innerText=Message.message
username_holder.innerText=username
div.appendChild(username_holder)
div.appendChild(p)
main.appendChild(div)
thread.appendChild(main)
threadholder.append(thread)
};
function add_message(message){
message=JSON.parse(message)
const chatholder=$("#Chatbox")
console.log(message.user.username)
const chat_message= document.createElement("li")
var div= document.createElement("div")
var p = document.createElement("p")
var sender=message.user.username
var text=message.message
p.innerText=text
div.appendChild(p)
chat_message.appendChild(div)
if(sender=="{{ user.username }}"){
chat_message.className="user"
}
else{
chat_message.className="other"
}
chatholder.prepend(chat_message)
}
$(document).ready(function(){
$("li").click(function(){
$("#Chatbox").empty()
var other_user= this.children[0].children[0].children[0].innerText
fetch(`/inbox/${other_user}`).then(response => response.json())
.then(data => data.messages.reverse().forEach(add_message))
})
})
and this is the function that returns the json response
view for json response
thread=Thread.objects.get_or_new(user=request.user,other_username=username)
messages=thread[0].chatmessage_set.all()
l= len(messages)
messages_serialized=[]
for i in range(l):
messages_serialized.append(json.dumps(ChatMessageSerializer(messages[i]).data))
print(messages)
return JsonResponse({"messages":messages_serialized})
and this Chat function is called via this url /inbox/<str:username>
I want a method that can help me get the thread open without reloading, and updates the url, I have used AJAX but it didn't help as it also took to me the page where it gave me the Json Response from django, changing the original page.
The failed AJAX implementation
<script>
var threads={{ Threads|safe }};
var messages={{ Messages|safe }};
const l=threads.length
const threadholder=$("#Threadbox")
for(i=0;i<l;i++){
var data=JSON.parse(threads[i])
var Message=JSON.parse(messages[i])
var username =data.second.username
if (username=="{{ user.username }}"){
username=data.first.username
}
var thread=document.createElement("li")
var main=document.createElement("a")
var div=document.createElement("div")
var username_holder=document.createElement("p")
div.className="thread"
var p=document.createElement("p")
p.innerText=Message.message
username_holder.innerText=username
div.appendChild(username_holder)
div.appendChild(p)
main.appendChild(div)
thread.appendChild(main)
threadholder.append(thread)
};
function add_message(message){
message=JSON.parse(message)
const chatholder=$("#Chatbox")
console.log(message.user.username)
const chat_message= document.createElement("li")
var div= document.createElement("div")
var p = document.createElement("p")
var sender=message.user.username
var text=message.message
p.innerText=text
div.appendChild(p)
chat_message.appendChild(div)
if(sender=="{{ user.username }}"){
chat_message.className="user"
}
else{
chat_message.className="other"
}
chatholder.prepend(chat_message)
}
$(document).ready(function(){
$("li").click(function(){
$("#Chatbox").empty()
var other_user= this.children[0].children[0].children[0].innerText
<script>
var threads={{ Threads|safe }};
var messages={{ Messages|safe }};
const l=threads.length
const threadholder=$("#Threadbox")
for(i=0;i<l;i++){
var data=JSON.parse(threads[i])
var Message=JSON.parse(messages[i])
var username =data.second.username
if (username=="{{ user.username }}"){
username=data.first.username
}
var thread=document.createElement("li")
var main=document.createElement("a")
var div=document.createElement("div")
var username_holder=document.createElement("p")
div.className="thread"
var p=document.createElement("p")
p.innerText=Message.message
username_holder.innerText=username
div.appendChild(username_holder)
div.appendChild(p)
main.appendChild(div)
thread.appendChild(main)
threadholder.append(thread)
};
function add_message(message){
message=JSON.parse(message)
const chatholder=$("#Chatbox")
console.log(message.user.username)
const chat_message= document.createElement("li")
var div= document.createElement("div")
var p = document.createElement("p")
var sender=message.user.username
var text=message.message
p.innerText=text
div.appendChild(p)
chat_message.appendChild(div)
if(sender=="{{ user.username }}"){
chat_message.className="user"
}
else{
chat_message.className="other"
}
chatholder.prepend(chat_message)
}
$(document).ready(function(){
$("li").click(function(){
$("#Chatbox").empty()
var other_user= this.children[0].children[0].children[0].innerText
$.ajax({
type: "GET",
url: {% url 'Chat' username=other_user %},
data: {'Messages': messages}
})
.done(function(response) {
console.log(reposne)
});
})
})
})
})

Your Django view is reloading the page because it's returning a response of content type HTML instead of, say, JSON.
Instead of
return render(request,'uno_startup/inbox.html',context={"Threads":thread_objs_list,"Messages":chat_objs_serialized})
Do something like
from django.http import JsonResponse
...
return JsonResponse({"Threads": thread_objs_list, "Messages": chat_objs_serialized})
You should still fetch this response from the front-end using JavaScript/AJAX.
As for how to change the URL without inducing a page refresh, refer to this answer.

Related

Updating the URLField of model with JavaScript

I have a page that displays some information about website admins such as username, skills, Instagram profile and bio. The admins are able to edit their profile information and the update is being saved using JavaScript fetch. When I click on the save button everything except the Instagram profile which is a URLField gets updated. For Instagram element to be updated I need to reload the page. How can I make it get updated without reloading the page? Everything is correct in the console log.
about.js:
document.addEventListener("DOMContentLoaded", function(){
const button = document.querySelectorAll("#edit_profile")
button.forEach(function(button){
button.onclick = function(){
const username = document.getElementById(`username_${memberID}`);
const skills = document.getElementById(`skills_${memberID}`);
const bio = document.getElementById(`bio_${memberID}`);
var instagram = document.getElementById(`instagram_${memberID}`).href;
let edit_username = document.createElement("textarea");
edit_username.setAttribute("rows", "1");
edit_username.innerHTML = username.innerHTML
edit_username.id = `edit_username_${memberID}`;
edit_username.className = `form-control username ${usernameID}`;
let edit_skills = document.createElement("textarea");
...
let edit_instagram = document.createElement("textarea");
edit_instagram.setAttribute("rows","1");
edit_instagram.innerHTML = instagram;
edit_instagram.id = `edit_instagram_${memberID}`;
edit_instagram.className = "form-control social-media";
const saveButton = document.createElement("button");
saveButton.innerHTML = "Save";
saveButton.id = `saveButton_${memberID}`;
saveButton.className = "btn btn-success col-3";
saveButton.style.margin = "10px";
document.getElementById(`edit_${memberID}`).append(edit_username);
...
document.getElementById(`edit_${memberID}`).append(edit_instagram);
document.getElementById(`edit_${memberID}`).append(saveButton);
// When the save button is clicked
saveButton.addEventListener("click", function(){
edit_username = document.getElementById(`edit_username_${memberID}`);
...
edit_instagram = document.getElementById(`edit_instagram_${memberID}`);
fetch(`/edit_profile/${memberID}`,{
method: "POST",
body: JSON.stringify({
username: edit_username.value,
skills: edit_skills.value,
instagram: edit_instagram.value,
bio: edit_bio.value,
})
})
.then(response => response.json())
.then(result => {
console.log(result);
if(result[`error`]){
cancel(memberID)
}
else {
username.innerHTML = result.username;
secusername.innerHTML = result.username;
skills.innerHTML = result.skills;
instagram = result.instagram;
bio.innerHTML = result.bio;
}
})
})
}
});
})
about.html:
{% for member in team_members %}
<div class="col" id="border">
<!--If user is admin, show edit button-->
{% if user.is_superuser %}
<div class="position-relative" id="edit_button_{{member.id}}" style="display: block;">
<button class="btn btn-lg position-absolute top-0 end-0" id="edit_profile" data-id="{{member.id}}" data-username="{{member.username}}">
<i class="fa fa-edit fa-solid" style="color: white; margin-right: 5px;"></i></button>
</div>
{% endif %}
<!--Edit form-->
<div class="form-group" id="edit_{{member.id}}">
</div>
<!--Display username,skills,socials and bio-->
<div id="remove_{{member.id}}" style="display: block;">
<h3 class="username" id="username_{{member.id}}">{{member.username}}</h3>
<p class ="skills" id="skills_{{member.id}}">{{member.skills}}</p>
<p><a class="social-media" href="{{member.instagram}}" id="instagram_{{member.id}}"><i class="fa-brands fa-instagram fa-solid" style="color: #e3c142; margin-right: 5px;"></i></a>
<a class="social-media" href="{{member.itch_profile}}" id="itch_{{member.id}}"><i class="fa-brands fa-itch-io" style="color: #e3c142;"></i></a>
<div class="bio">
<strong class="username" id="secusername_{{member.id}}" style="font-size: large;">{{member.username}}, </strong><p id="bio_{{member.id}}">{{member.bio}}</p>
</div>
</div>
</div>
</div>
{% endfor %}
views.py:
#csrf_exempt
def edit_profile(request, member_id):
if request.method != "POST":
return JsonResponse({"error": "POST request required."}, status=400)
team_members = Team.objects.get(id = member_id)
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
username = body['username']
skills = body['skills']
instagram = body['instagram']
itch_profile = body['itch_profile']
bio = body['bio']
Team.objects.filter(id=member_id).update(username=f'{username}',skills=f'{skills}',instagram=f'{instagram}',itch_profile=f'{itch_profile}',bio=f'{bio}')
return JsonResponse({"message": "Successful", "username": username, "skills": skills, "instagram":instagram, "itch_profile":itch_profile, "bio": bio}, status=200)
You're assigning the instagram variable to the href attribute of the edit_instagram element, rather than its value. Since the fetch request is sending the value of the edit_instagram element, the Instagram URL will not be updated in the backend if the instagram variable is assigned to the href attribute.
So you can change the line of code where you assign the instagram variable to the following:
var instagram = document.getElementById(`instagram_${memberID}`).value;
Also, you need to update the 'instagram' element value after successful fetch call:
instagram.href = result.instagram;
This should update the Instagram URL field in the backend without requiring a page reload.
Assigned the instagram variable to the element itself instead of its href:
var instagram = document.getElementById(`instagram_${memberID}`)
Then, updated the href after the fetch call as Nova suggested:
instagram.href = result.instagram;

Loading category tags with load more button

I am new to jQuery. I have implemented a "load more" button on my blog app using jQuery, however the categories tags doesn't get displayed on the html when I click on that button.
Everything works fine so far, I can't just display the tags on the post card, it keeps returning undefined.
Note: I'm getting my categories from a many to many field relationship
Here are my views:
def home(request):
post = BlogPost.objects.all()[0:5]
total_post = BlogPost.objects.count()
context = {'post': post, 'total_post':total_post}
return render(request,'blog/home.html', context)
def load_more(request):
# get total items currently being displayed
total_item = int(request.GET.get('total_item'))
# amount of additional posts to be displayed when i click on load more
limit = 3
posts = list(BlogPost.objects.values()[total_item:total_item+limit])
print(BlogPost.objects.all())
data = {
'posts':posts,
}
return JsonResponse(data=data)
Template:
<div class="blogpost-container">
<div class="blogposts" id="blog-content">
{% for post in post %}
<div class="post">
<img id="img-src" src="{{post.image.url}} " image-url="{{post.image.url}}" alt="">
<p><strong>{{post.title}}</strong></p>
{% for category in post.category.all%}
<h3>{{category}}</h3>
{%endfor%}
<a id="post-detail-link" href="{% url 'detail' post.id %}" detail-url="{% url 'detail' post.id %}"><h2>{{post.summary}}</h2></a>
</div>
{%endfor%}
</div>
</div>
<div class="add-more" data-url='{% url "load_more" %}'id="add-btn">
<button type="button" class="more-content">load more</button>
</div>
<div class="alert no-more-data" role="alert" id="alert">
No more post to load!!!
</div>
{{total_post|json_script:"json-total"}}
JS file:
const loadBtn = document.getElementById('add-btn')
const total_post = JSON.parse(document.getElementById('json-total').textContent);
const alert = document.getElementById('alert')
function loadmorePost(){
const content_container = document.getElementById('blog-content');
var _current_item =$('.post').length;
$.ajax({
url:$('.add-more').attr('data-url'),
type:'GET',
data:{
'total_item':_current_item
},
beforeSend:function(){
alert.classList.add('no-more-data')
},
success:function(response){
const data = response.posts
alert.classList.add('no-more-data')
data.forEach(posts => {
const imageurl = 'media/'+posts.image
const detailurl = 'post/'+posts.id;
const category = posts.category;
content_container.innerHTML +=`<div class="post" id=${posts.id}>
<img id="img-src" src=${imageurl} image-url="{{post.image.url}alt="">
<p><strong>${posts.title}</strong></p>
<h3>${category}</h3>
<a id="post-detail-link" href=${detailurl}><h2>${posts.summary}</h2></a>
</div>`
})
if (_current_item == total_post){
alert.classList.remove('no-more-data')
loadBtn.classList.add('no-more-data')
}
else{ loadBtn.classList.remove('no-more-data')
alert.classList.add('no-more-data')
}
},
error:function(err){
console.log(err);
},
});
};
loadBtn.addEventListener('click', () => {
loadmorePost()
});

How to fetch image from django FileResponse using javascript

I would like to render an image in html using javascript, and the image is being retrieved from a django view using the fetch api. I think I am close but can't figure out how to display image in browser using javascript.
view #1: (url: builds/imgretrieve/int:device/)
class imgRetrieve(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, *args, **kwargs):
device = self.kwargs['device']
deviceVals = CustomUser.objects.get(id=device)
buildImg = ImageRequest.objects.filter(author = deviceVals).latest("dateAdded")
return FileResponse(buildImg.image)
When I access this view directly using a browser, it displays an image as expected.
However when I want the javascript to display it in a different view, it just displays [object Response] instead of the image.
Here is how I am attempting to do this:
view #2 (url: builds/chamberCam/int:device/)
class chamberCamView(LoginRequiredMixin,TemplateView):
template_name = 'chamberCam.html'
login_url = 'login'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
device = self.kwargs['device']
deviceVals = CustomUser.objects.get(id=device)
CustomUser.objects.filter(id = device).update(imgRequested = True, imgReceived = False,)
context['deviceName'] = deviceVals.UserDefinedEquipName
context['deviceID'] = deviceVals.id
return context
html
{% block body %}
<p hidden id = "id">{{ deviceID }}</p>
<div class="">Chamber cam for {{deviceName}}</div>
<div class="imageDiv" id = "image">
</div>
{% load static %}
<script src="{% static 'camera/chamberCam.js' %}"></script>
{% endblock %}
chamberCam.js
let deviceID = document.getElementById("id").innerHTML;
getImg(deviceID)
function getImg(deviceID){
fetch('http://127.0.0.1:8000/builds/imgretrieve/' + deviceID + '/')
.then(function(res){
return res;
})
.then(function(data) {
let image = document.getElementById("image");
console.log(data)
image.innerHTML = `
<img>${data}</img>
`;
})
.catch(function(err){
console.log(err);
});
}
I was over complicating it..
I replaced the javascript code with:
let deviceID = document.getElementById("id").innerHTML;
addimage(deviceID)
function addimage() {
var img = new Image();
img.src = 'http://127.0.0.1:8000/builds/imgretrieve/' + deviceID + '/'
image.appendChild(img);
}

How to submit a Django form using JavaScript (jQuery)

I'm working on a web app project. I had a problem with file upload. Then I realized that my team mate changed the default submit button in create_form.html. It works like in 5. and 6. and i need to collect file data as well.
What should I add to .js files to submit and save file?
forms.py
class DocumentUpload(forms.ModelForm):
class Meta:
model = Form
fields = ('file',)
models.py
class Form(TimeStampedModel, TitleSlugDescriptionModel):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=512)
is_final = models.BooleanField(default=False)
is_public = models.BooleanField(default=False)
is_result_public = models.BooleanField(default=False)
file = models.FileField(null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('form-detail', kwargs={'slug': self.slug})
views.py
def create_form(request):
if request.method == 'POST':
user = request.user
data = ParseRequest(request.POST)
print(data.questions())
print(data.form())
parsed_form = data.form()
parsed_questions = data.questions()
# tworzy formularz o podanych parametrach
formfile = DocumentUpload(request.POST, request.FILES or None)
if formfile.is_valid():
form = formfile.save(commit=False)
print(form)
form.author = user
form.title = parsed_form['title']
form.is_final = parsed_form['is_final']
form.is_result_public = parsed_form['is_result_public']
form.description = parsed_form['description']
form.save()
# zapisuje pytania z ankiety wraz z odpowienimi pytaniami
for d in parsed_questions:
question = Question(form=form, question=d['question'])
question.save()
# dla kazdego pytania zapisz wszystkie opcje odpowiadania
for opt in d['options']:
option = Option(question=question, option=opt)
option.save()
return render(request, 'forms/form_form.html', {})
else:
form = DocumentUpload()
return render(request, 'forms/form_form.html', {'form': form})
create_form.html
Here I have to submit {{ form.as_p }} <- I have to submit this input in JS**
{% block content %}
<form method="post" id="form" enctype='multipart/form-data'>
{%csrf_token %}
<div class="form-group">
{% csrf_token %}
<label for="form-title">Tytuł formularza</label>
<input id="form-title" class="form-control" type="text"
placeholder="Tytuł" required/>
</div>
{{ form.as_p }}
.... more divs ...
<input class="btn btn-default" type="submit" value="zapisz"/>
</form>
{% endblock %}
collect_data.js
This is my function called to save inputs from create_form.html instead of:
<input class="btn btn-default" type="submit" value="zapisz"/>
but I don't know how to save input from:
{{ form.as_p }}
function collect_data() {
var csrftoken = getCookie('csrftoken');
var data = {
form_title: $('#form-title').val(),
is_final: $('#form-is-final').prop('checked'),
is_public: $('#form-is-public').prop('checked'),
is_result_public: $('#form-is-result-public').prop('checked'),
description: $('#description').val(),
questions: [],
num_questions: num_questions,
csrfmiddlewaretoken: csrftoken
};
for (var k = 0; k < num_questions; k++) {
var my_data = {};
var question_k = $('#question-' + k);
my_data.question = question_k.find('#question-text').val();
my_data.answer_type = question_k.find('select').val();
my_data.options = [];
for (var j = 0; j < num_question_options[k]; j++) {
var answer = question_k.find('#answer-' + j).val();
if (answer !== '') {
my_data.options.push(answer)
}
}
my_data.num_options = my_data.options.length;
data.questions.push(my_data)
}
return data
}
submit_data_create.js
$(document).ready(function (event) {
$(document).on('submit', '#form', function (e) {
e.preventDefault();
var data = collect_data();
$.ajax({
type: 'POST',
url: '/form/create/',
data: data,
success: function (data, textStatus) {
window.location.href = '/form/list/'
},
fail: function (response) {
alert('Coś poszło nie tak.');
}
});
})
});

Django View on Ajax call

I'm creating a catalogue page. On this page I want to allow user to filter the products.
So I created a sidebar with checkboxes and input texts.
I would like that every time the user changes the filter parameters, the catalogue is updated.
this is my code:
html for sidebar (filter):
<h3>Filtri:</h3>
<b>Marca:</b><br>
{% for marca in marche %}
<input type="checkbox" title="{{ marca.nome }}" value="{{ marca.nome }}" name="marca" class="marca" onclick="filtra()"> {{ marca.nome }} <br>
{% empty %}
<p>Nessuna Marca è ancora stata inserita.</p>
{% endfor %}
<br>
<b>Portata:</b> <br>
Maggiore di
<input type="text" title="portata" name="portata" id="portata" class="textbox-filtro" maxlength="4" onblur="filtra()"> kg
<br><br>
<b>Sollevamento:</b> <br>
Maggiore di
<input type="text" title="sollevamento" id="sollevamento" class="textbox-filtro" maxlength="4" onblur="filtra()"> mt
<br><br>
<b>Trazione:</b><br>
{% for tra in trazione %}
<input type="checkbox" title="{{ tra.trazione }}" value="{{ tra.trazione }}" id="{{ tra.trazione }}" class="trazione" onclick="filtra()"> {{ tra.trazione }} <br>
{% empty %}
<p>Nessuna Trazione è ancora stata inserita</p>
{% endfor %}
<br>
<b>Idroguida:</b><br>
{% for idro in idroguida %}
<input type="checkbox" title="{{ idro.idroguida }}" value="{{ idro.idroguida }}" id="{{ idro.idroguida }}" class="idroguida" onclick="filtra()"> {{ idro.idroguida }} <br>
{% empty %}
<p>Nessuna Idroguida è ancora stata inderita</p>
{% endfor %}
As you can see, I've 5 filter groups: Marca (brand), Portata (carrying capacity), Sollevamento (lift), Trazione (traction) and Idroguida (power steering).
Every time you edit these values, the javascript function filtra() is called... so onblur for text input and onclick for checkboxes.
Here the javascript code:
<script>
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function filtra() {
var marche_selezionate = [];
var marca_check = document.getElementsByClassName('marca');
for(var i = 0; i < marca_check.length; i++){
if(marca_check[i].checked){
marche_selezionate.push(marca_check[i].value);
}
}
marche_selezionate = marche_selezionate.join(',');
var portata_selezionata = document.getElementById('portata').value;
var sollevamento_selezionata = document.getElementById('sollevamento').value;
var trazioni_selezionate = [];
var trazione_check = document.getElementsByClassName('trazione');
for(i = 0; i < trazione_check.length; i++){
if(trazione_check[i].checked){
trazioni_selezionate.push(trazione_check[i].value);
}
}
var idroguida_selezionate = [];
var idroguida_check = document.getElementsByClassName('idroguida');
for(i = 0; i < idroguida_check.length; i++){
if(idroguida_check[i].checked){
idroguida_selezionate.push(idroguida_check[i].value);
}
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var postUrl = "{% url 'carrellielevatori:carrellielevatori' %}";
$.ajax({
url: postUrl,
type: 'POST',
data: {'marche_selezionate': marche_selezionate},
success: function(result){
alert('success');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
so, after setting up csrf token, in way to avoid the error "403 forbidden", I start looking and all the parameters and set up the 5 variables that I would like to pass at the view in way to filter up the catalogue.
I've also added some alert in the ajax call in way to know if it's successful or not. It is. The alert with "success" appear.
The problem is that everything stops here.
In fact, it seems nothing happens in the view.
here the code of the view:
def carrellielevatori(request):
lista_carrelli = Carrelli.objects.all()
lista_marche = Marche.objects.all()
lista_trazione = Trazione.objects.all()
lista_idroguida = Idroguida.objects.all()
footerForm = MailForm()
method = 'get'
if request.is_ajax():
method = 'ajax'
return render(request,
'carrellielevatori/carrellielevatori.html',
{
'title': 'Carrelli Elevatori - Giemme Lift s.r.l.',
'footerForm': footerForm,
'year': datetime.now().year,
'carrelli': lista_carrelli,
'marche': lista_marche,
'trazione': lista_trazione,
'idroguida': lista_idroguida,
'method':method,
})
to understand if it works, I've set up the variable method to "get" and displayed it on the page. Then in the ajax "if", I change the value to "ajax".
So it should change, right? the text remains "get" and never changes to "ajax".
This is a first try to see if it works. Once I know this work I'll proceed to filter the query that with the products. But if this does not work it's useless.
PS. Yes in the ajax call I pass just one parameters. This is to know if it works. Later I will proceed adding the other parameters in the data field.
To conclude, can you please tell me why does not enter in the in if request.is_ajax()':
Is this in not the right way, how can I filter the oringal query?
I've also tried with if request.method == 'POST', but i get the same result.
Here’s how I would do it:
#csrf_exempt
def carrellielevatori(request):
lista_carrelli = Carrelli.objects.all()
lista_marche = Marche.objects.all()
lista_trazione = Trazione.objects.all()
lista_idroguida = Idroguida.objects.all()
footerForm = MailForm()
method = 'get'
if request.is_ajax():
method = 'ajax'
return JsonResponse({
'title': 'Carrelli Elevatori - Giemme Lift s.r.l.',
'footerForm': footerForm,
'year': datetime.now().year,
'carrelli': lista_carrelli,
'marche': lista_marche,
'trazione': lista_trazione,
'idroguida': lista_idroguida,
'method':method,
})
In the JS:
function filtra() {
var marche_selezionate = [];
var marca_check = document.getElementsByClassName('marca');
for(var i = 0; i < marca_check.length; i++){
if(marca_check[i].checked){
marche_selezionate.push(marca_check[i].value);
}
}
marche_selezionate = marche_selezionate.join(',');
var portata_selezionata = document.getElementById('portata').value;
var sollevamento_selezionata = document.getElementById('sollevamento').value;
var trazioni_selezionate = [];
var trazione_check = document.getElementsByClassName('trazione');
for(i = 0; i < trazione_check.length; i++){
if(trazione_check[i].checked){
trazioni_selezionate.push(trazione_check[i].value);
}
}
var idroguida_selezionate = [];
var idroguida_check = document.getElementsByClassName('idroguida');
for(i = 0; i < idroguida_check.length; i++){
if(idroguida_check[i].checked){
idroguida_selezionate.push(idroguida_check[i].value);
}
}
var postUrl = "{% url 'carrellielevatori:carrellielevatori' %}";
$.post(postUrl, {'marche_selezionate': marche_selezionate},
function(result){
alert('success');
}).fail(function (data, status, xhr) {
alert(xhr.status);
alert(thrownError);
});
}

Categories