load html instead of a div Django - javascript

javascript:
$('.openDiv').click(function () {
var id = $(this).attr('id');
var csrf_token = $("#csrf_token").val();
$.ajax({
data: {
csrfmiddlewaretoken: ('{{csrf_token}}'),
id: id,
},
type: 'POST',
url: '/setting/save-reporter/',
success: function () {
$('#authorisedreporter').load('save_reporter.html');
}
});
});
index.html
<div id="authorisedreporter" {% if not registerform.errors %}style="display:none"{% endif %}>
<form method="post" action="." id="reporter-form">
{% csrf_token %}
<table width="100%">
""""""""
</table></form></div>
save_reporter.html
<form method="post" action="." id="{{ id }}">
{% csrf_token %}
<table width="100%">
"""""""""
</table></form>
I am using ajax with js,after successfull ajax call,the div is replaced by save_reporter.html.But i am getting 404 page not found error in console.If i am not using $('#authorisedreporter').load('save_reporter.html'); ,i am getting the required output in console.While trying to show the output in template i did that and i am getting the error.Need help.

You can't use the jQuery load function to load templates from Django. Templates are not standalone HTML pages: as you already know from writing the other views, you need to write a URL and a view to render the template and return it.
What you should be doing is getting your /setting/save-reporter/ view to return the rendered template, and insert that result in your div via .html():
success: function(response) {
$('#authorisedreporter').html(response);

Related

Modify twig variable through js without reloading page

I have an array of objects which are rendered through for loop in twig template. I want to apply a filter-like mechanism where after selecting a category from a filter, list of elements in twig would update without refreshing a page and contain elements only from chosen category.
Until now I managed to pass chosen category value through ajax to Symfony controller, parse it, encode to JS and send it as a response and fetch it via ajax.
Here's some code:
//variable passed to twig
return $this->render('#Ad/ad_list.html.twig', [
'adList' => $adList,
]);
//An ajax call
$.ajax({
url : $form.attr('action'),
type: "POST",
data : filters,
complete: function(html) {
console.log(html['responseJSON'])
}
});
//creating a response
$response = JsonResponse::fromJsonString($jsonContent);
$response->prepare($request);
$response->send();
{% for ad in adList|slice(0, 9) %}
...
{% endfor %}
Is it possible to update passed variable ($adList) to twig via JS, so it would render elements from response?
Thanks to brombeer and DarkBee help I achieved my goal. I did it by:
Creating new template which holds list of elements,
Rendering this new template in main template and passing there updated value
main template:
<section>
{% include '#Ad/ad_list_container.html.twig' %}
</section>
ad_list_container template:
<div id="ad-list">
{% for ad in adList %}
...
{% endfor %}
</div>
ajax call:
$.ajax({
url : $form.attr('action'),
type: "POST",
data : filters,
success: function(response) {
$('#ad-list').html(response);
}
});
php controller:
return $this->render('#Ad/ad_list_container.html.twig', [
'adList' => $adList
]);

I want to add product in cart without refreshing page with AJAX and Django

Nothing will ne happened when I submit product in the the cart. I want to use AJAX without refreshing page.
When I submit the console message will be displayed.
I'm trying to use AJAX first.
Trying to add product in the cart without refreshing page.
I need help please :)
Views Django
def add_cart(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update_qt']
)
return JsonResponse({'status': 'success'})
Form
from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator
class CartProductForm(forms.Form):
quantity = forms.IntegerField(initial=1)
update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
HTML Code
<form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form">
{{ cart_product_form }}
{% csrf_token %}
<a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a>
</form>
JS Code
$(".buy-product").on('click', function(e){
e.preventDefault();
var product_id = $(this).attr('data-id')
var quantity = 1
console.log(product_id)
console.log(quantity)
data = {
'product_id': product_id,
'quantity': quantity
}
var point='/cart/add/'+product_id+'/'
$.ajax({
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
url: point,
type: 'POST',
data: data,
success: function(data){
console.log('success')
console.log(csrftoken)
}
})
})
You need to add csrftoken in data: {csrfmiddlewaretoken':csrftoken}. Also I don't see when you initialize your variables, but I think is just example. Check this answer for more: link
You can prevent form from refreshig the page and then do whatever you need with your JS code:
<form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form" onsubmit="myFunction(event)">
...
</form>
<script>
function myFunction(event){
event.preventDefault();
}
</script>

Building a like post in flask using ajax and jquery fails

I am building a simple flask blog and there I am trying to implement like functionality using ajax and jquery. It works without ajax but the page reloads. So I need to use the ajax but when I am using ajax then I got my site redirected to the JSON file which is not expected. Please Help me with this. The code is
<div class="likers" id = 'result{{ slide.id }}'>
{% if current_user.has_liked_slide(slide) %}
<a class="unlike" id="unlike_{{slide.id}}" href="{{ url_for('like_action', slide_id=slide.id, action='unlike') }}">unlike</a>
{% else %}
<a class="like" id="like_{{slide.id}}" href="{{ url_for('like_action', slide_id=slide.id, action='like') }}">like</a>
{% endif %}
<div id = 'like-count'>
{{ slide.likes | count }}
</div>
</div>
#app.route('/like/<int:slide_id>/<action>', methods = ['GET', 'POST'])
#login_required
def like_action(slide_id, action):
slide = Slide.query.filter_by(id=slide_id).first_or_404()
if action == 'like':
current_user.like_slide(slide)
db.session.commit()
return jsonify({'slide_id': slide_id, 'action': action})
if action == 'unlike':
current_user.unlike_slide(slide)
db.session.commit()
return jsonify({'slide_id': slide_id, 'action': action})
$(document).ready(function(event) {
$('.like, .unlike').click(function(){
var id = this.id;
var split_id = id.split('_');
var text = split_id[0];
var slide_id = split_id[1];
$.ajax({
url: '/like/<int:slide_id>/<action>',
type: 'post',
data : {slide_id:slide_id, action:text},
dataType:'html',
success: function(data){
$("like_" + slide_id).html(data);
$('unlikes_' + slide_id).html(data);
}
});
});
});

AJAX JSON response doesn't refresh for tag at Django template

I have built a view in views.py that returns a JSON when user press a button. The page updates simple html divs (last_bid, credits, message) without reloading but I have some {% for %} tags that don't refresh although JSON response is updated with extra data.
template.html script
<script>
$('#bid').on('submit', function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: '{% some url %}',
datatype: 'json',
data: {
some data
},
success: function(data) {
$('#last-bid').html(data.last_bid);
$('#credits').html(data.credits);
$('#message').html(data.message);
$('#registered_players').html(data.registered_players);
}
});
});
template.html
<div id="registered_players">
{% for i in registered_players %}
{{ i.auction_player__user__username }}
{% endfor %}
</div>
JSON
{"registered_players": [{"auction_player__user__username": "admin"}, {"auction_player__user__username": "minos"}], "last_bid": "8.10", "credits": 612, "message": ""}
Instead of targeting the div "registered_players". Either you need to loop through your JSON data and replace every single player Or you need to remove the old players html and add your new HTML.
Please provide your HTML by inspecting the html page for more clear answer.
Thank you all for the help. Managed to solve this by looping through JSON response.
var player_list = "<ul>";
for (var i=0; i< data.registered_players.length; i++){
player_list += "<li>" + data.registered_players[i].auction_player__user__username + "</li>";
}
player_list += "</ul>"
$('#registered_players').html(player_list);

Looking to rename Django Ajax "like" button, but not working

Currently my button functions, but I've placed it inside of a django for loop. I'd like to move the js logic to a separate file, but first I need to give it a better name. Here is a snippet of my code:
{% for post in posts %}
.....
<script type="text/javascript">
function toggleLike{{post.id}}(){
$.ajax({
url: "{% url 'photo_blog-post_like_api' post.id %}",
success: function(data) {
$("#likeCount{{post.id}}").html(data.like_count + ' likes');
$('#imageElement{{post.id}}').html(data.img);
}
});
};
</script>
<a id=imageElement{{post.id}} onclick="toggleLike{{post.id}}()"><img src="/media/nav_buttons/liked.svg" height="17" width="17"></a>
....
<post info here>
....
{% endfor %}
When I remove the {{post.id}} from the function name, and onclick call, the button only functions for the post on the bottom of the page. All of the other buttons toggle the information for that one post. How can I give this function a general name, but still have it interact uniquely with each post?
You shouldn't be doing this as part of the name anyway. The post id is a parameter. The only collocated part is working out how to pass it to the Django URL tag
function toggleLike(post_id){
$.ajax({
url: "{% url 'photo_blog-post_like_api' "00000" %}".replace("00000", post_id)
success: function(data) {
$("#likeCount" + post_id).html(data.like_count + ' likes');
$('#imageElement' + post.id).html(data.img);
}
});
};
</script>
<a id=imageElement{{post.id}} onclick="toggleLike({{post.id}})"><img src="/media/nav_buttons/liked.svg" height="17" width="17">

Categories