Search routing broken in wampserver but not in production - javascript

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 ?

Related

Django 1.10 - Ajax - order of operations?

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.

Fade out pop-up window on click of a button?

I've followed this tutorial to implement a pop-up email newsletter sign-up to add to my Shopify theme which uses fancybox.js & cookie.js. Everything works fine except when you enter an email address & click 'Sign Up' even though an additional tab opens to complete the Mailchimp sign up process, on the original shop tab, the email pop-up stays open as though nothing has changed.
I wondered if there is a way I could adapt the code so that on click of 'Sign Up' the new tab opens as normal but the email pop-up fades out so when the user goes back to the shop the pop-up has disappeared. I'm not great with JS so any help would be really appreciated!
My current code:
theme.liquid -
Liquid HTML:
{% if settings.popup_newsletter_enable %}
<div id="email-popup" style="display: none;" >
{% include 'popup-newsletter-form' %}
</div>
{% endif %}
JS:
{{ 'jquery.fancybox.js' | asset_url | script_tag }}
<script type="text/javascript">
(function($) {
// set a variable for the cookie check
var check_cookie = $.cookie('popup_box');
// check whether the cookie is already set for this visitor
if( check_cookie != 'active' ){
// if the cookie does not exist do the following:
// (1) set the cookie so it's there for future visits (including an expiration time in days)
$.cookie('popup_box', 'active', {
expires: 3,
path: '/'
});
// (2) trigger the fancybox pop up, specifying that it's inline
$( '#trigger' ).fancybox({
type: 'inline',
});
setTimeout(function () {
$('#trigger').eq(0).trigger('click'); // make the click event happen on load
}, 5000);
}
})(jQuery); // this is a noconflict wrapper for WP
</script>
popup-newsletter-form.liquid (snippet include):
Liquid HTML:
<!-- Mailchimp Form Integration -->
{% if settings.newsletter_form_action != blank %}
{% assign form_action = settings.newsletter_form_action %}
{% else %}
{% assign form_action = '#' %}
{% endif %}
<form action="{{ form_action }}" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" target="_blank" class="input-group">
<input type="email" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.newsletter_email' | t }}" name="EMAIL" id="mail" class="input-group-field" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}" autocorrect="off" autocapitalize="off">
<span class="input-group-btn">
<input type="submit" class="btn" name="subscribe" id="subscribe" value="{{ 'general.newsletter_form.submit' | t }}">
</span>
</form>
$('#pro_image').click(function(){
$("#pro_image").fancybox({
closeSpeed : 250,
closeEasing : 'swing',
closeOpacity : true,
closeMethod : 'zoomOut',
});
})
;
Try this one.
Usually they put js inside header, also possible to put it any where inside tag, but they say better to place in at the bottom of code ( inside ) to let all code receive by browser and the js execute.

Django, update page with ajax

I study Django and want to use ajax. Read some examples, but have problem.
I need to show all posts by click on link with name site.
view:
def archive(request, page_number=1):
posts = BlogPost.objects.all()
current_page = Paginator(posts, 3)
if request.is_ajax():
t = loader.get_template("archive_ajax.html")
else:
t = loader.get_template("archive.html")
c = Context({'posts': current_page.page(page_number),
'username': auth.get_user(request).username})
return HttpResponse(t.render(c))
base.html:
<h1><a class="refresh" >mysite.example.com</a></h1> (I need click it and update posts )
<div class="content">
<div>
{% block content %}
{% endblock %}
</div>
</div>
archive.html:
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
{% include "archive_ajax.html" %}
{% endfor %}
{% endblock %}
archive_ajax.html (problem not here, I mean firstly I need to solve problem which higher ):
<h2> {{ post.title }} </h2>
<p> author: {{ post.author.username }}</p>
<p> {{ post.timestamp | date:"l, F jS, Y" }} </p>
<p> {{ post.body }} </p>
In base.html includ jquery: <script src="/static/jquery-1.11.1.min.js" type="application/javascript"></script>
And I try to write code
$(document).ready(function(){
$(".refresh").click(function(){
console.log('clicked');
$(".content").load("/blog/");
});
});
when I click on link I see it on the place where might be posts:
{"content": "
\n
\u0430\u0432\u0442\u043e\u0440:
\n
\n
\n", "status": 200, "statusText": "OK"}
In command line I see "GET /blog/ HTTP/1.1" 200 151
I try another way and write:
$(document).ready(function(){
$(".refresh").click(function(){
$.ajax({
type: "GET",
url: "/blog/",
success : function(newdata) {
$('.content').html(newdata);
}
});
});
});
And now I can see nothing in place where might be posts.
In command line I see "GET /blog/ HTTP/1.1" 200 151`
In view I add print
if request.is_ajax():
t = loader.get_template("archive_ajax.html")
print('it is query'`)
and in command line I see message - it's query, for ajax and js.
I use python 2.7.3, Django 1.6.5 and jquery 1.11.1.min.
Thank you all! I find my mistake, it was in ajax and in template archive_ajax.html. It's my inattention I think. In template I forgot to add loop for {{posts}}. now it's:
{% for post in posts %}
<h2> {{ post.title }} </h2>
<p>автор: {{ post.author.username }}</p>
<p> {{ post.timestamp | date:"l, F jS, Y" }} </p>
<p> {{ post.body }} </p>
{% endfor %}
And in ajax I correct it:
$('.content').html(newdata.content);
It is not a good practice to write:
<h2> {{ post.title }} </h2>
Take a look at the {% url %} template tag.
Edit - Disclaimer: the current user has not enough rate to comment. That's why this apparently answer-less answer is posted here.

Django: Jquery click function not working in Ajax

I have been working through the Tango with Django exercises to cut my teeth into Django. Almost done but having a problem with the Ajax part.
Ajax function to auto_add a page is not being called. Idk what the problem is since the other functions are being called.
On the shell prompt, there is no call to the ajax function at all. Help needed.
Pertinent code attached. It is the same as on the website link above.
static/rango-ajax.js
$('.rango-add').click(function(){
var catid = $(this).attr("data-catid");
var title = $(this).atrr("data-title");
var url = $(this).attr("data-url");
$.get('/rango/auto_add_page/', {category_id: catid, url: url, title: title}, function(data){
$('#pages').html(data);
me.hide();
});
});
templates/rango/category.html
{% if user.is_authenticated %}
<button data-catid="{{category.id}}" data-title="{{ result.title }}" data-url="{{ result.link }}" class="rango-add btn btn-mini btn-info" type="button">Add</button>
{% endif %}
rango/views.py
#login_required
def auto_add_page(request):
context = RequestContext(request)
cat_id = None
url = None
title = None
context_dict = {}
if request.method == 'GET':
cat_id = request.GET['category_id']
url = request.GET['url']
title = request.GET['title']
if cat_id:
category = Category.objects.get(id=int(cat_id))
p = Page.objects.get_or_create(category=category, title=title, url=url)
pages = Page.objects.filter(category=category).order_by('-views')
#Adds our results list to the template context under name pages.
context_dict['pages'] = pages
return render_to_response('rango/page_list.html', context_dict, context)
rango/urls.py
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^goto/$', views.track_url, name='track_url'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^auto_add_page/$', views.auto_add_page, name='auto_add_page'),
Complete code is at this link.
your code is good, the only thing what you have to do is to define your template in /tango/templates/rango/page_list.html. This template have the following code:
{% if pages %}
<ul>
{% for page in pages %}
<li>
{{ page.title}}
{% if page.views > 1 %}
({{page.views}} views)
{% elif page.views == 1 %}
({{page.views}} view)
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<strong> No Pages currently in category. </strong>
{% endif %}
And inside of your category template you must define the following code:
% if category %}
{% if user.is_authenticated %}
Add a new Page <br>
{% endif %}
{% if pages %}
<div id="pages">
<ul>
{% for page in pages %}
<li>
{{ page.title}}
{% if page.views > 1 %}
({{page.views}} views)
{% elif page.views == 1 %}
({{page.views}} view)
{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% else %}
<strong> No Pages currently in category. </strong>
{% endif %}
{% else %}
The specified category {{ category_name }} does not exist!
{% endif %}
I'm working through this section of the tutorial now and just want to add to Héctor's answer. To avoid duplicating the code to display the list of pages I did the following:
I added a get_page_list() method to tango/rango/templatetags/rango_extras.py, similar to the get_category_list() method used to display a list of categories in an earlier section of the tutorial.
from rango.models import Page
#register.inclusion_tag("rango/page_list.html")
def get_page_list(category):
pages = Page.objects.filter(category=category) if category else []
return {'pages': pages}
Then we just need to load rango_extras and call the get_page_list() method in tango/templates/rango/category.html.
{% extends 'rango/base.html' %}
{% load rango_extras %}
<!-- Existing code -->
{% if category %}
<!-- Existing code to show category likes and like button -->
<div id="page_list">
{% get_page_list category %}
</div>
<!-- Existing code to show search if user is authenticated -->
{% else %]
The specified category {{ category_name }} does not exist!
{% endif %}
This allows you to display the list of pages when a category page is first loaded and then refresh it if a category is added from the search area, without having to duplicate any code.

This is deleting my page, Ajax jQuery

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);

Categories

Resources