For some reason my ajax success call deletes my page content and replaces the entire page with "success"
{% extends "base.html" %}
{% block title %}Plan{% endblock %}
{% block content %}
<div id="form">
<a>Welcome to planning</a>
{{form.as_p}}
<button id="button">Submit</button>
</div>
<div id="content"> </div>
<script>
$('button#button').click(function() {
$.ajax({
url:'submit',
success: function(data) {
$('div#content').text(data);
},
});
});
</script>
{% endblock %}
Here are my views being called:
def planning(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('loginregistration.views.login'))
form = planForm()
return render(request, 'plan.html', {'form':form})
def submitplan(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('loginregistration.views.login'))
if request.is_ajax:
POST = request.POST
msg = "Success"
print request.POST
return HttpResponse(msg)
Can someone also tell me ajax is suppose to recognize my html ids?
$('div#content') is probably your pages id.
Change
<div id="content"> </div>
to
<div id="data"> </div>
and do
$('div#data').text(data);
Related
I'm trying to embed tweets using python django and javascript.
This is my views.py currently:
def tweets(request):
context_dict = {}
tweets_today = Tweet.objects.order_by('-favorites')
tweets_today = tweets_today[:15]
context_dict['tweets_today'] = tweets_today
return render(request, 'summary/tweets.html', context_dict)
And my HTML (base.html has the twitter JS script)
{% extends 'base.html' %}
{% block body_block %}
<div class="container">
{% for tweet in tweets_today %}
<div class="block social-block social-twitter">
<div id="container_{{ forloop.counter }}">
</div>
</div>
<script>
window.onload = (function () {
twttr.widgets.createTweet(
'{{ tweet.tweet_id }}',
document.getElementById('container_{{ forloop.counter }}'),
{
theme: 'dark'
}
);
});
</script>
{% endfor %}
</div>
{% endblock %}
For some reason this is only embedding one tweet. Is it because of the window.onload?
I'm using django-el-pagination, a django package that allows ajax pagination. I'm paginating a queryset of Comment (a list of comments). The queryset is inside comments.html, which is inside comments_base.html, which is inside article.html (the parent view). Here's my views:
def article(request, category, id, extra_context=None):
name = resolve(request.path).kwargs['category']
instance = get_object_or_404(Post, id=id, entered_category=name)
new_comments_list = Comment.objects.filter(destination=id, parent_id=0).order_by('-timestamp')
template = 'article.html'
page_template = 'comments.html'
if request.is_ajax():
template = page_template
context = {
'id': id,
'comment_list': new_comments_list,
'page_template': page_template,
'instance': instance,
}
if extra_context is not None:
context.update(extra_context)
return render(request, template, context)
comments_base.html
{% block comments_base %}
<div class="commentsContainer">
<div class="endless_page_template">
{% include 'comments.html' %}
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{% static 'js/el-pagination/js/el-pagination.js' %}"></script>
<script>
$.endlessPaginate({
});
</script>
{% endblock %}
</div>
{% endblock %}
comments.html
{% block comments %}
{% paginate 10 comment_list %}
{% for i in comment_list %}
{% if i.parent_comment %}
<div class="comment_shell hasParent">
{% else %}
<div>
{% endif %}
<div class='comment_div' data-comment_id="{{ i.id }}">
<div class="left_comment_div">
<div class="username_and_votes">
<h3><a class='username_foreign'>{{ i.user }}</a></h3>
{% for j in i.score.all %}
<span class="upvotes">{{ j.upvotes }}</span>
<span class="downvotes">{{ j.downvotes }}</span>
{% endfor %}
</div>
<br>
<p>{{ i.comment_text }}</p>
</div>
</div>
{% include 'comments.html' with comment_list=i.replies.all %}
</div>
{% endfor %}
{% show_pages %}
{% endblock %}
So when I go to the next set of comments in the pagination, jQuery doesn't work. And I assume this is because of it being appended or dynamic content. So I used the on() method which other answers say to do. However it still doesn't work. I'll just show a simple example to show it doesn't work:
$('.upvotes').on('click', function() {
$(this).css('color', '#fff');
});
Doesn't change color onclick. So is there any reason why it still doesn't work, and how can I fix it?
This sounds like an application of jquery's on method overload that uses the additional selector argument:
.on( events [, selector ] [, data ], handler )
From the jquery documentation:
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.
So this should work:
$('body').on('click', '.upvotes', function() {
$(this).css('color', '#fff');
});
Or in place of the 'body' selector use any other element that exists in the DOM at the time that javascript is executed.
I am using Ajax with Django 1.10 to implement a like functionality ( a user likes an image posted by another user) on my website. I have the following code :
The views file :
#ajax_required
#login_required
#require_POST
def image_like(request):
image_id = request.POST.get('id')
action = request.POST.get('action')
if image_id and action:
try:
image = Image.objects.get(id=image_id)
if action == 'like':
image.users_like.add(request.user)
else:
image.users_like.remove(request.user)
return JsonResponse({'status':'ok'})
except:
pass
return JsonResponse({'status':'ko'})
def image_detail(request, id, slug):
image = get_object_or_404(Image, id=id, slug=slug)
return render(request,
'images/image/detail.html',
{'section': 'images',
'image': image})
In base.html :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script>
<script>
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$(document).ready(function(){
{% block domready %}
{% endblock %}
});
</script>
And finnaly in the detail.html :
{% extends "base.html" %}
{% block title %}{{ image.title }}{% endblock %}
{% block content %}
...
{% with total_likes=image.users_like.count users_like=image.users_like.all %}
<div class="image-info">
<div>
<span class="count">
<span class="total">{{ total_likes }}</span>
like{{ total_likes|pluralize }}
</span>
<a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button">
{% if request.user not in users_like %}
Like
{% else %}
Unlike
{% endif %}
</a>
</div>
{{ image.description|linebreaks }}
</div>
<p> Image liked by :</p>
<div class="image-likes">
{% for user in image.users_like.all %}
<div>
<p>{{ user.last_name }}</p>
</div>
{% empty %}
Nobody likes this image yet.
{% endfor %}
</div>
{% endwith %}
{% endblock %}
{% block domready %}
$('a.like').click(function(e){
e.preventDefault();
$.post('{% url "images:like" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like').data('action');
// toggle data-action
$('a.like').data('action', previous_action == 'like' ?
'unlike' : 'like');
// toggle link text
$('a.like').text(previous_action == 'like' ? 'Unlike' :
'Like');// update total likes
var previous_likes = parseInt($('span.count .total').text());
$('span.count .total').text(previous_action == 'like' ?
previous_likes + 1 : previous_likes - 1);
}
}
);
});
{% endblock %}
While I mostly understand the code itself, I need help understanding in what orders the requests, the callback functions and everything else is executed ... something like : ,users clicks the like button, that information is passed to the server , it is being manipulated, data-base modified , sent back, the page changes ...
Tell me if any extra code ( models, urls etc. ) is needed. Could't post everything.
views.py
class PortfolioListView(AjaxListView):
model = Portfolio
context_object_name = "portfolios"
template_name = "portfolios/portfolio_list.html"
page_template = 'portfolios/portfolio_list_page.html'
portfolio_list.html
{% extends "skeleton/base.html" %}
{% load el_pagination_tags %}
{% block content %}
<div class="test-class">
hi-1
</div>
<section>
<div class="container">
<div class="row">
<div class="col-md-offset-1 col-md-10">
{% include page_template %}
</div>
</div>
</div>
</section>
{% endblock %}
{% block custom_js %}
<script src="{% static 'el-pagination/js/el-pagination.js' %}"></script>
<script>$.endlessPaginate({});</script>
<script type="text/javascript">
$(document).ready(function(){
$(".test-class").click(function(){
alert("ji");
});
});
</script>
{% endblock %}
portfolio_list_page.html
<div>
{% lazy_paginate portfolios %}
<div class="test-class">
hi-2
</div>
<div class="test-class">
hi-3
</div>
{% show_more %}
</div>
When I load portfolio_list.html page and click hi-1, it shows alert.
But when I click show more and click hi-2 or hi-3, it doesn't show alert.
I want to show alert even I clicked hi-2 or hi-3.
How can I implement this?
p.s Actually, this is a kinda very simple code for showing clearly what I want to do.
What I eventually want to do is to execute whole javascripts code(e.g _owl_carousel(), _flexslider(), _popover(), _lightbox(), _mixitup(),, etc) after loading portfolio_list_page so that this whole javascript function also can be applied to newly loaded page
I have a problem with my Symfony2 Website. I have a search function which work fine in production but not in wamp.
My twig file :
{% extends "::base.html.twig" %}
{% block title %}Membres en attente de validation{% endblock %}
{% block body %}
{% if confirmation != null %}<div id="confirmationValidation">Nouveau tutoré accepté : {{ confirmation }}</div>{% endif %}
<form id="form_recherche_validation" action="{{ path('paces_user_validation_recherche') }}" method="post">
{{ form_widget(form) }}
<input type="submit" value="Rechercher" />
</form>
<!-- Loading -->
<div class="center-align">
<div class="preloader-wrapper small active loading_validation">
</div>
</div>
<div id="resultats_recherche_validation">
{% include 'PACESUserBundle:Validation:liste.html.twig' with {'tutores' : tutores} %}
</div>
{% endblock %}
Problem is that search is working thanks to a script :
$(".loading_validation").hide();
$("#resultats_recherche_validation").hide();
$("#form_recherche_validation").submit(function() {
$(".loading_validation").show();
$("#resultats_recherche_validation").show();
var numero = $("#paces_user_validationRechercheForm_numero").val();
var nom = $("#paces_user_validationRechercheForm_nom").val();
var prenom = $("#paces_user_validationRechercheForm_prenom").val();
var DATA = {numero: numero, nom: nom, prenom: prenom};
var request = $.ajax({
type: "POST",
url: "{{ path('paces_user_validation_recherche')}}",
data: DATA,
success: function(data) {
$('#resultats_recherche_validation').html(data);
$(".loading_validation").hide();
}
});
return false;
});
This script is normally loaded in the page's twig file. In wamp, all scripts doesn't work except those I put in my base.html.twig. So I created a custom.js file which loads the scripts for the whole website.
According to Chrome developer tools, it should be a route problem :
No route found for "POST /validation/%7B%7B%20path('paces_user_validation_recherche')%7D%7D" (from "http://localhost/trunk/web/validation/")
I searched for a whole day but I don't find an answer.
Do you have an idea ?