Can't add comment with ajax - javascript

I'm trying to add comment using ajax.
Here is my ajax code:
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = {{article.id}};
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "get",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = "comment"><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
});
});
Here is my form of adding comment in django template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>
Trying to debug, I noticed that it doesn't even step into ajax body. What am I doing wrong then?
I've done ajax query with counting likes and had success in that.

Try this
HTML
</div>
{% if username %}
<form action="#" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="text" name = "article" value="{{ article.id }}" id = "article_id">
<input type="text" name = "comment" value="comment goes here" id = "comment_text">
<input type="submit" class="button" value="???????? ???????????" id = "add_comment">
</form>
{% endif %}
</div>
jQuery
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = $('#article_id').val();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "POST", /*i belive you are posting data to BE api*/
data:{'comment':"your comment goes here"}, /* use this get what given in input $("#comment_text").val()*/
success: function(result){
/*process data after success call*/
}
});
});
});

Change to the following:
JS Code:
$(document).ready(function(){
$("#comment_form").submit(function(event){
event.preventDefault();
var article_id = $(this).find('.article_id').value();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "post",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = 'comment'><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
return false;
});
});
Django Template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="hidden" class="article_id" value="{{ article.id }}" />
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>

Related

django adding real time probelm

this is html include that add the product and make multi adding random , once it dosnt make duplicate , and once work normally .
{% load i18n %}
{% load static %}
<form >
<div class="tab_content active" data-tab="fruits">
<div class="row ">
{% for productss in my_products %}
<div class="col-lg-3 col-sm-6 d-flex " >
<div class="productset flex-fill" >
<div class="productsetimg">
{% if productss.product_icon %}
<img src="{% url 'productss.product_icon.url' %}" alt="img">
{% else %}
<img src="{% static 'assets/img/product/product1.jpg' %}" alt="img">
{% endif %}
<h6>{% translate "Qty" %}: {{productss.bpq_real_quantity}}</h6>
<div class="">
<i class=""></i>
</div>
</div>
<div class="productsetcontent">
<h4><span id="productee_namee{{productss.id}}">{{productss}}</span></h4>
<h6>{{productss.bpq_product_sell_price}}</h6>
<div class="increment-decrement">
<div class="input-groups">
<input type="button" value="-" onclick="decrementValue{{productss.id}}()" class="button-minus dec button">
<input type="text" name="child" value="1" class="quantity-field" id="plus_field{{productss.id}}" name="quantity_required">
<input type="button" value="+" onclick="incrementValue{{productss.id}}()" class="button-plus inc button" >
<input type="submit" value="{% translate "Add" %}" id="add_item_{{productss.id}}">
</div>
</div>
</div>
</div>
</div>
</form>
<script>
console.log('plus_field{{productss.id}}')
function incrementValue{{productss.id}}()
{
var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('plus_field{{productss.id}}').value = value;
}
function decrementValue{{productss.id}}()
{
var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10);
value = isNaN(value) ? 0 : value;
if (value > 1 ) {
value--;
}
document.getElementById('plus_field{{productss.id}}').value = value;
}
</script>
{% comment %} var quantity = $("#quantity_required").val();
$.ajax({
type: "POST",
url: {% url 'view_detail' %},
data: search_word,
success: function(result){
alert("Success");
}
}); {% endcomment %}
{% comment %}
$('#add_item_{{productss.id}}').hide();
setTimeout(function()
{
$('#add_item_{{productss.id}}').show();
}, 1000); {% endcomment %}
{% csrf_token %}
<script>
$(document).ready(function(e){
$(document).on('click','#add_item_{{productss.id}}',function(e){
e.preventDefault();
$('#add_item_{{productss.id}}').attr('disabled', true);
setTimeout(function()
{
$('#add_item_{{productss.id}}').attr('disabled', false);
}, 1000);
var $this = $(this);
var quantity = $("#plus_field{{productss.id}}").val();
var customer = $("#cstname").val();
//console.log(productname);
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
$.ajax({
url:"{% url 'orders:add_item_resturant' productss.pk %}",
type: "POST",
dataType: "json",
data: {
'quantity':quantity,
'customer':customer,
'csrfmiddlewaretoken':csrftoken,
},
success:function(response){
//console.log('success addess')
$('#add_item_update').html(response['result']);
totalprice();
},
});
});
});
</script>
{% endfor %}
</div>
</div>
{% comment %}
<div>
<input id="search" name="search" type="text" class="query-search" placeholder="Search...">
<input onclick="setGetParameter()" type="button" class="btn btn-primary" value = "View Details"/>
</div>
<script>
function setGetParameter(){
var search_word = $("#search").val();
$.ajax({
type: "POST",
url: {% url 'view_detail' %},
data: search_word,
success: function(result){
alert("Success");
}
});
}
</script>
and in views :
def search_view(request):
if request.method == "POST":
search_word = request.POST['data']
{% endcomment %}
this is views.py
def add_item_resturant(request,pk):
print(f"This is request.POST: {request.POST}")
current_user=request.user
customer=Customer.objects.get(customer_name=request.POST['customer'])
CstPoints=customer.customer_Points
user_branch=request.user.user_profile.user_branch
current_order=OrderDetail.objects.select_related('order_order').select_related('order_product_name').filter(order_order__order_progress="In Progress",order_order__order_who_created=current_user)
current_product=BrancheProductQuantity.objects.get(id=pk)
branch_tax=current_product.bpq_branch_name.branch_Tax
real_quantity=current_product.bpq_real_quantity
sell_price=current_product.bpq_product_sell_price
returned_order=Order.objects.get(order_who_created=current_user,order_progress="In Progress")
get_quantity = request.POST['quantity']
if float(real_quantity) - float(get_quantity) < 0 :
messages.warning(request,"Product Quantity is Error and the Quantity of it=" + str(real_quantity) +"and you enter" + get_quantity)
return redirect("orders:add_resturant_order")
if request.method =="POST" :
order_detail , created =OrderDetail.objects.get_or_create(
order_order = returned_order,
order_product_name = current_product)
qfloat=float(get_quantity)
sfloat=float(sell_price)
total_item=float(qfloat*sfloat)
tax=(total_item*branch_tax/100)
price_iclude_tax=tax+total_item
order_detail.order_tax_value=float(tax)
order_detail.order_product_name=current_product
order_detail.order_product_price=current_product.bpq_product_sell_price
order_detail.order_product_quantity=float(get_quantity)
order_detail.order_detail_total=float(total_item)
order_detail.total= float(price_iclude_tax)
order_detail.order_biller_user = str(current_user)
order_detail.order_branch = str(user_branch)
order_detail.save()
final_total_value=current_order.aggregate(Sum('total'))['total__sum']
final_tax_value=current_order.aggregate(Sum('order_tax_value'))['order_tax_value__sum']
full_sub_total=current_order.aggregate(Sum('order_detail_total'))['order_detail_total__sum']
returned_order=returned_order.refresh_from_db()
html = render_to_string('include/add_item_resturant.html',{'CstPoints':CstPoints,'final_total_value':final_total_value,'final_tax_value':final_tax_value,'full_sub_total':full_sub_total,'returned_order':returned_order,'order_detailed':current_order, request:request})
return JsonResponse({'result':html})
enter image description here
I want to solve this problem it make adding product twice and may be 3 or 4 times as showd in page I donst know why is this problem appear.

The submission form was duplicated in the ajax response page using Django views.py

I am trying to use a form to submit the parameter to views.py and get the results back to the html. However, the form part was repeatedly display in the page.
enter image description here
Here is my views.py
def fund_main_py(request):
last_trade_date = request.GET['last_trade_date']
print(last_trade_date)
plot_div1, plot_div2 = fund_main_main(last_trade_date)
return render(request, 'optionsfund.html', context={'plot_div1': plot_div1, 'plot_div2': plot_div2})
Here is my stocksettle.js
$(document).ready(function(){
$("#btn_submit").click(function(){
document.getElementById("result").innerHTML = '抓取中.... 若期限過長,請稍後1分鐘!';
var stock_code = $("#stock_code").val();
var last_trade_date = $("#last_trade_date").val();
$.ajax({
type: "GET",
url: "/fund_main_py",
data:{
"stock_code":stock_code,
"last_trade_date":last_trade_date
},
success: function (Data) {
$("#result").html(Data);
},
error: function (e) {
console.log(e);
}
});
})
});
Here is my optionsfund.html
<table border="0">
<tr>
<td><fieldset>
<span> 指數/股票代號 :</span>
<input type="button" id="btn_submit" value=" 查詢 ">
</fieldset></td>
</tr>
</table>
<span id="result">
<span id="plot1">
{% autoescape off %}
{{ plot_div1 }}
{% endautoescape %}
</span><br><br>
<span id="plot2">
{% autoescape off %}
{{ plot_div2 }}
{% endautoescape %}
</span>
</span><br><br>

Django Form dropdown fill with values

I have a from with fields I created in Django models.py. One of the fields is:
res_person_1 = models.TextField(verbose_name="Odgovorna osoba 1")
HTML page is:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Prijavite nesukladnost</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Prijava</button>
</div>
</form>
</div>
When I inspect the HTML page, ID of object is 'id_res_person_1'. At the page load I run script to get from database all users, which should fill the 'res_person_1' field and that field should be dropdown.
Script is:
<script type="text/javascript">
var endpoint = '/call_jquery_korisnici/'
var korisnik_ime_prezime = []
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
korisnik_ime_prezime = data.korisnik_ime_prezime
console.log(korisnik_ime_prezime)
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
</script>
I don't know how to fill that field and how to make it dropdown. It doesn't work with:
$("#id_res_person_1").html(korisnik_ime_prezime);
document.getElementById('id_res_person_1').value = korisnik_ime_prezime;
If I console output var korisnik_ime_prezime: (2) ["TestName1 TestLastname1", "TestName2 TestLastname1"]
You can use replaceWith to replace your textarea with select-box then use each loop to iterate through your return response from server and then append option inside your select-box.
Demo code :
$(document).ready(function() {
var korisnik_ime_prezime = []
/*$.ajax({
method: "GET",
url: endpoint,
success: function(data) {*/
//just for demo
korisnik_ime_prezime = ["TestName1 TestLastname1", "TestName2 TestLastname1"] // data.korisnik_ime_prezime
//replcae textarea with slect
$("#id_res_person_1").replaceWith("<select name='id_res_person_1' id='id_res_person_1' class='form-control'></select>")
//loop
$(korisnik_ime_prezime).each(function(i) {
$("#id_res_person_1").append("<option>" + korisnik_ime_prezime[i] + "</option>") //append options
})
/*},
error: function(error_data) {
console.log("error")
console.log(error_data)
}
})*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form method="POST" enctype="multipart/form-data">
<textarea id="id_res_person_1"></textarea>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Prijava</button>
</div>
</form>

ajax in django success function is not working

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

how to use hashtag regex with ajax?

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.

Categories

Resources