I know there are lot of questions with the same tag. But I tried few solutions of them and it didn't worked. Following is my code and I can't figure out how to fix it.
<script>
function setPrice(){
var price = $(".variation_select option:selected").attr("data-price")
var sale_price = $(".variation_select option:selected").attr("data-sale-price")
if (sale_price != "" && sale_price != "None" && sale_price != null ) {
$("#price").html("<h3>" + sale_price + " <small class='og-price'>" + price + "</small></h3>");
} else {
$("#price").html(price);
}
}
setPrice()
$(".variation_select").change(function(){
setPrice()
})
$("#submit-btn").click(function(event){
event.preventDefault();
var formData = $("#add-form").serialize();
console.log(formData);
$.ajax({
type:'GET',
url: "{% url 'cart' %}",
data: formData,
success: function(data){
console.log(data)
},
error: function(response, error){
console.log(response)
console.log(error)
}
})
// $("#add-form").submit()
})
</script>
Error it shows on browser inspect elements is at
var price = $(".variation_select option:selected").attr("data-price")
Even though I don't think its necessary but following is the HTML code:
<div class='col-sm-4'>
<form id='add-form' method='GET' action="{% url 'cart' %}">
<p id='jquery-message' class='lead'>
</p>
{% if object.variation_set.count > 1 %}
<h3 id='price'>{{ object.variation_set.first.price }}</h3>
<select name='item' class='form-control variation_select'>
{% for vari_obj in object.variation_set.all %}
<!-- <option data-img="http://www.spirit1059.com/pics/Feeds/Articles/2015611/118317/Beach.jpg" data-price="{{ vari_obj.price }}" value="{{ vari_obj.id }}">{{ vari_obj }}</option> -->
<option data-sale-price="{{ vari_obj.sale_price }}" data-price="{{ vari_obj.price }}" value="{{ vari_obj.id }}">{{ vari_obj }}</option>
{% endfor %}
</select>
{% else %}
<input type="hidden" name='item' value='{{ object.variation_set.first.id }}' />
<h3 id='price'>{% if object.variation_set.first.sale_price %}
{{ object.variation_set.first.sale_price }}
<small class='og-price'>{{ object.variation_set.first.price }}</small>
{% else %}
{{ object.variation_set.first.price }}
{% endif %}
</h3>
{% endif %}
<br/>
<input class='form-control' type='number' name='qty' value='1' />
<br/>
<input id='submit-btn' type='submit' value='Add to Cart' class='btn btn-default' />
</form>
Jquery Script file includes following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="{% static 'js/ie10-viewport-bug-workaround.js' %}"></script>
Please ignore Django template language if you are not familiar with it. You can still have the idea about jQuery error skipping the template language.
after using jquery script, use this code instead:
$(document).ready(function(){
setPrice()
$(".variation_select").change(function(){
setPrice()
})
});
If you're using jQuery in your page you need to include a jquery liberary in your html page. Because initially in javascript $ is nothing but $ means jquery which tells the browser that its a jquery function.
Include this jquery liberary in your webpage.
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
add jQuery script before your JS code
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
define variable "$". You can achieve this by adding a wrapper to your JS code:
<script>
(function($){
// your code here
})(jQuery)
</script>
MMh try including jquery before your tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Related
I am new in ajax as well as Django. I try to put ajax in my code to check that in the signup page if some user is already having one email then that email can't use for new users and disable the button else if the email does not exist then the user can be created.
ajaxCode
$(document).on('blur', 'input[name="email"]', function(){
$.ajax({
type:'POST',
url:'/stock/checkemail/',
data:{
email:$("#email").val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
$('input[type="submit"]').attr('disabled', 'true')
},
failure:function(){
$('input[type="submit"]').removeAttr('disabled');
}
})
});
url.py
path('checkemail/',Emailser.as_view()),
views.py
class Emailser(View):
def post(self, request):
em = request.POST['email']
print(em)
try:
user = User.objects.get(email=em)
return HttpResponse('true')
except:
return HttpResponse('false')
In views.py print(em) is also printing mail that type in field but don't know why is not working.
template
{% extends 'base.html' %}
{% block content %}
{% load static %}
<div>
<h2>Sign Up</h2>
{% if error %}
{{error}}
<br/>
{% endif %}
<form method="post" id="signup" >
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary" >Signup</button>
</form>
</div>
<script src="{% static 'assets/signup.js' %}" ></script>
{% endblock %}
try this inside succcess function
$('input[type="submit"]').disabled = true;
$(document).on('blur', 'input[name="email"]', function(){
$.ajax({
type:'POST',
url:'/stock/checkemail/',
data:{
email:$("#email").val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(response){
response ? $('input[type="submit"]').attr('disabled', 'true') : $('input[type="submit"]').removeAttr('disabled');
},
failure:function(error){
console.log(error);
}
})
});
I already did a hashtag in the base.html it is working. like if anyone type something with #something it will replace by the javascript in the html with links. It is working on the post list. so i want to work it on the comments. But the comments have ajax method that's why it is not working in the comments. can we keep them both(AJAX and Hashtag).
my base.html:
$(document).ready(function() {
$("p").each(function(data) {
var strText = $(this).html();
console.log('1. strText=', strText);
var arrElems = strText.match(/#[a-zA-Z0-9]+/g);
console.log('arrElems=', arrElems);
$.each(arrElems, function(index, value){
strText = strText.toString().replace(value, ''+value+'');
});
console.log('2. strText=', strText);
$(this).html(strText);
});
});
(#the ajax method for comments)
$(document).on('submit', '.comment-form', function(event){
event.preventDefault();
console.log($(this).serialize());
$("p").each(function(data) {
var strText = $(this).html();
console.log('1. strText=', strText);
var arrElems = strText.match(/#[a-zA-Z0-9]+/g);
console.log('arrElems=', arrElems);
$.each(arrElems, function(index, value){
strText = strText.toString().replace(value, ''+value+'');
});
console.log('2. strText=', strText);
$(this).html(strText);
});
});
$.ajax({
type: 'POST',
url: $(this).attr('action'),
cache: false,
data: $(this).serialize(),
dataType: 'Json',
success: function(response) {
$('.main-comment-section').html(response['form']);
$('textarea').val('');
$('.reply-btn').click(function() {
$(this).parent().parent().next('.replied-comments').fadeToggle()
$('textarea').val('');
});
},
error: function(rs, e) {
console.log(rs.responseText)
},
});
});
my comments.html:
<form method="post" enctype="multipart/form-data" class="comment-form" action=".">
{% csrf_token %}
{{ comment_form.as_p }}
<input type="submit" value="submit" class="btn-btn-outline-success">
</form>
<div class="container">
{{ comments.count }} comment{{ comments|pluralize }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<div class="options">
{% if comment.user == user %}
delete
{% endif %}
</div>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user }}</cite>
<button type="button" name="button" class="reply-btn btn btn-outline-dark btn-sm">reply</button>
</footer>
</blockquote>
<div class="replied-comments container mt-2" style="display:none;">
{% for reply in comment.replies.all %}
<blockquote class="blockquote">
<p class="mb-0"><small>{{ reply.content }}</small></p>
<footer class="blockquote-footer"><small>by <cite title="Source Title">{{ reply.user }}</cite></small></footer>
</blockquote>
{% endfor %}
<div class="form-group-row">
<form method="post" class="reply-form" action="." enctype='multipart/form-data'>
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}">
{{ comment_form.as_p }}
<input type="submit" value="submit" class="btn-btn-outline-success">
</form>
</div>
</div>
{% endfor %}
the ajax method raise errors like the ajax is not working the hashtag is not working.
well i just have to put the script into the comments.html not in the base.html.
I wish I could show the form that I selected in my combo (between student and employee)
The problem is probably my jquery because by changing the values that hides or displays the form but I want her displays the form desired by changing the value of my combo
student --> StudentForm
employee --> EmployeeForm
But when I change the value of my list the form stays the same ...
here is my code with my forms
user_profile.html
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
{% extends "polls/base.html" %}
{% block title %}Création d'un profil{% endblock %}
{% block bodyId %}userProfilePage{% endblock %}
<!-- <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> -->
{% block content %}
<script type="text/javascript">
function displayRightForm() {
if ($("#profileType").val() == 'student') {
$('#employeeForm').hide();
$('#studentForm').show();
}
else {
$('#studentForm').hide();
$('#employeeForm').show();
}
}
$(document).ready(displayRightForm);
$('#profileType').change(displayRightForm);
</script>
<h1>Création d'un compte</h1>
<form>
<p>
<label for="profileType">Vous êtes :</label>
<select id="profileType">
<option value="student" {% if studentForm.is_bound %} selected="selected" {% endif %}>Étudiant</option>
<option value="employee" {% if employeeForm.is_bound %} selected="selected" {% endif %}>Employé</option>
</select>
</p>
</form>
<form action="register" method="GET" id="studentForm">
{{ studentForm.as_p }}
{% csrf_token %}
<p>
<input type="hidden" name="profileType" value="student" />
<input type="submit" value="Créer un compte" />
</p>
</form>
<form action="register" method="GET" id="employeeForm">
{{ employeeForm.as_p }}
{% csrf_token %}
<p>
<input type="hidden" name="profileType" value="employee" />
<input type="submit" value="Créer un compte" />
</p>
</form>
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
{% endblock %}
The jquery works because if I pass
if ($("#profileType").val() == 'student') {
$('#employeeForm').hide();
$('#studentForm').show();
}
in
if ($("#profileType").val() == 'student') {
$('#employeeForm').show();
$('#studentForm').show();
}
This shows me two good form to follow
I use this link for the jquery, It is correct?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
Thanks for your time guys !
Change your script as below :
<script type="text/javascript">
$(document).ready(function() {
displayRightForm();
});
function displayRightForm() {
if ($("#profileType").val() == 'student') {
$('#employeeForm').hide();
$('#studentForm').show();
} else {
$('#studentForm').hide();
$('#employeeForm').show();
}
}
$('select').on('change', function() {
displayRightForm();
});
</script>
i have a form and i use jQuery for submit and work without refresh page..
$('#formnotifica').submit(
function(event){
event.preventDefault();
term = $(this).serialize();
url = $(this).attr('action');
$.post(
url,
term,
function(data){
}
)
}
);
Now i would refresh only my content the form and the date after click of submit or some second..
I use this code when i tried but give me another page Symfony and give me problems..
$(document).ready(function() {
$("#aggiorna").load("");
var refreshId = setInterval(function() {
$("#aggiorna").load("" + Math.random());
}, 1000);
});
Where #aggiorna is the "ID" of my .. How can i do for refresh my result of query in controller?? Thanks and sorry for my english
THIS IS THE CODE HTML
<div id="aggiorna">
<ul>
{% for n in notifications %}
{% if n.is_displayed == 0 %}
<li>
<form id="formnotifica" action="{{ path('profilo_index', {'id': n.id}) }}" method="post">
<input name="id" type="hidden" value="{{ n.id }}" />
<button class="submit" id="submit" type="submit" >{{n.text|raw}}</button>
</form>
</li>
{% else %}
<li>{{n.text|raw}}
</li>
{% endif %}
{% endfor %}
</ul>
</div>
In the controller there is only DQL query for update a field in my db
Remove:
event.preventDefault();
I have created a view that generates posts and each post have a comments_set which produces all the comments made by user. When new comment is posted, below function is executed.
$("#comment-post-button").click(function(){
var event_id = document.getElementById('event-id').value;
var url= '/post-comments/'+event_id +'/';
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:document.getElementsByName('comment-post-content')[0].value
}
$.post(url , data, function(){
$("#refresh-comments").load("/comments/" + event_id + '/', function(){
$("#comment-post-content").val("");
});
});
$("#comment-post-content").val("");
return false;
});
The problem is that the page contains multiple posts and each comment submission button has the same id "comment-post-button". So the above function works only for the top post and not for the rest. I can see what the problem is but don't know how to solve this. Please help.
Here is the html markup:
{% for event in events %}
<div class="post">
<div class="post-right">
<div class="post-author">{{ event.author.first_name }}</div>
<div class="post-content">{{ event.description }}</div>
<div class="post-bar">
<div class="post-likes">{{ event.up_votes }}<img src="/site-media/static/images/like.png" /></div>
<div class="post-dislikes">{{ event.down_votes }}<img src="/site-media/static/images/dislike.png" /></div>
<div class="post-timestamp">{{ event.pub_date }}</div>
Comment
</div>
<div class="post-comment">
<form method="post" action="/post-comments/{{ event.id }}/">
{% csrf_token %}
<input type="text" id="comment-post-content" name="comment-post-content" maxlength="200" placeholder="Add a comment..." />
<input type="hidden" id="event-id" value="{{ event.id }}">
<input type="submit" id="comment-post-button" class="comment-post-button" value="Post comment" />
</form>
</div>
<div id="refresh-comments" class="comments">
{% include "comments.html" %}
</div>
</div>
<div class="post-left">
<img src="../FestJanta/site-media/static/images/post.jpg" />
</div>
</div>
{% endfor %}
comments.html:
{% for comment in event.comment_set.all|slice:"3" %}
<div class="comments-right">
{{ comment.author.first_name }}
{{ comment.content }}<br>
<div class="comment-timestamp">{{ comment.pub_date }}</div>
</div>
<div class="comments-left"><img src="../FestJanta/site-media/static/images/comment.jpg" /></div>
{% endfor %}
Final working solution:
$(".comment-post-button").click(function(){
var btn = $(this);
var currentPost = btn.parents('.post');
var event_id = currentPost.find('.event-id').val();
var url= '/post-comments/'+event_id +'/';
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:currentPost.find('input[name="comment-post-content"]').val()
}
$.post(url , data, function(){
$(currentPost.find('.refresh-comments')).load("/comments/" + event_id + '/', function(){
$(currentPost.find('.comment-post-content')).val("");
});
});
return false;
});
Remove id and add class:
<input type="hidden" class="event-id" value="{{ event.id }}">
Do something like this:
$('.comment-post-button').click(function(){
var $btn = $(this);
var $currentPost = $btn.parents('.post');
var event_id = $currentPost.find('.event-id').val();
//...
});
Find each element in $currentPost scope:
Instead of this:
content: document.getElementsByName('comment-post-content')[0].value
Do this:
content: $currentPost.find('input[name="comment-post-content"]').val()
You could do the following:
Identify all post buttons, e.g. by a class like .comment-button
Use the .on() notation of jQuery
Pass the event and use its target property to identify the DOM element that triggered the event
Use traversion to get the correct DOM element of the post
The result should look something like this (untested):
Markup (I basically just got rid of the IDs; not sure how/if django handles this automatically):
{% for event in events %}
<div class="post">
<div class="post-right">
<div class="post-author">{{ event.author.first_name }}</div>
<div class="post-content">{{ event.description }}</div>
<div class="post-bar">
<div class="post-likes">{{ event.up_votes }}<img src="/site-media/static/images/like.png" /></div>
<div class="post-dislikes">{{ event.down_votes }}<img src="/site-media/static/images/dislike.png" /></div>
<div class="post-timestamp">{{ event.pub_date }}</div>
Comment
</div>
<div class="post-comment">
<form method="post" action="/post-comments/{{ event.id }}/">
{% csrf_token %}
<input type="text" name="comment-post-content" maxlength="200" placeholder="Add a comment..." />
<input type="hidden" name="event-id" value="{{ event.id }}">
<input type="submit" class="comment-post-button" value="Post comment" />
</form>
</div>
<div class="comments">
{% include "comments.html" %}
</div>
</div>
<div class="post-left">
<img src="../FestJanta/site-media/static/images/post.jpg" />
</div>
</div>
{% endfor %}
Javascript:
$("body") // Could be any ancestor, body is not the best option
.on('click', '.comment-post-button' function(ev){
var clickTarget = ev.target, // The element clicked on
postElement = $(clickTarget).closest('.post'), // the div enclosing a post
commentSection = $(postElement).find(".comments"), // the div enclosing the comments
commentInputField = $(clickTarget).siblings("[name='comment-post-content']"),
event_id = $(clickTarget).siblings("[name='event-id']").val(),
url= '/post-comments/'+event_id +'/';
// Not sure what this token is, so I will not change that part
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content: commentInputField.val()
}
$.post(url , data, function(){
$(commentSection).load("/comments/" + event_id + '/', function(){
$(commentInputField ).val("").prop('disabled', false); // In the callback, empty and reenable
});
});
$(commentInputField ).prop('disabled', true); // I guess disabling the field makes sense
return false;
});
An additional advantage is that you will end up with only one click handler. Note that the solution could be optimized (e.g. by improving the selectors). In addition, jslint will give some warnings.
to give each post & post_Comment_button a unique id, as suggested by someone, change the markup as follows:
{% for event in events %}
<div class="post" id="post_{{forloop.counter}}">
[...]
<input type="submit" id="comment-post-button_{{forloop.counter}}" class="comment-post-button" value="Post comment" />
then change the js function as follows:
$("#comment-post-button").click(function(event){
var buttonNr = event.target.id.replace('comment-post-button_', '');
var postId = 'post_' + buttonNr;
$("#" + postId)... --> and do whatever with it..