Ajax "on change" doesn't fire - javascript

I have a form, which I would like to pre-populate depending on selected item in a drop down list. The HTML code:
My Ajax.js looks like:
$("#domain_selected").on('change', function() {
$.ajax({
url: '/returndomaindetails',
data: {
domainselect: $("#domain_selected").val()
},
success: function(data, status, xhr) { // success callback function
if (data.length > 1) {
var js = JSON.parse(data)
var domainname = js['domainname']
var domainarchitect = js['domainarchitect'];
$('#domainname').empty().append(domainname)
$('#domainarchitect').empty().append(domainarchitect)
$("#domain_details").show()
} else {
$("#domain_details").hide()
}
},
error: function(jqXhr, textStatus, errorMessage) { // error callback
}
});
})
HTML
<div class="card">
<div class="card-body">
<h4 class="card-title">Change Domain</h4>
<form action="{{ url_for('changedomain') }}" method="post">
<div class="form-row">
<div class="form-group col-md-4">
<label for="domain_selected" class="col-form-label">Select domain</label>
<select id="domain_selected" name="domain_selected" class="form-control">
<option>Choose</option>
{% for x in domain %}
<option value="{{x}}">{{ x }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-row" name="domain_details" id="domain_details" style="display: none">
<div id="domain_name" class="form-group col-md-4">
<label class="col-form-label">Domain Name</label>
<input type="text" class="form-control" name="domainname" id="domainname" placeholder="">
</div>
<div class="form-group col-md-4">
<label class="col-form-label">Domain architect</label>
<input type="text" class="form-control" name="domainarchitect" id="domainarchitect" placeholder="">
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Change Domain</button>
</div>
{% block scripts %}
<script src="{{ url_for('static', filename='js/ajax.js') }}"></script>
{% endblock %}
Now, on the flask endpoint /returndomaindata , I have just a simple print statement to get indication that the GET request arrived, however it doesn't.
#app.route('/returndomaindetails', methods=["GET"])
def returndomaindetails():
if request.method=="GET":
print("got the GET request")
domainselect=request.args.get('domainselect')
data=Domains.returndomaindetails(domainselect)
print(data)
return json.dumps(data)
Seems like the "on change" event is not firing. There are absolutely no errors in the console. Similar functions work without problem in the same file.

It turned out to be indentation problem - a space before the function

Related

how to push multivalues from many element with same class or id in ajax

I have created a form , that user can append the additional column that need to that form, for example I have column name in the form , if people want to add more column name , they just press the add button , and then select element for the column name and it will be added, so it will have 2 select element with same class, but the problem is , I dont know how to send the data with ajax so django views that can get the data.Every time that I try to print the result , it will print as [] which means: failed to push the data
here's the code
html
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<form class="form-horizontal style-form" action="#">
<div class="form-group">
<label class="control-label col-md-3">Database Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
<!-- <li></li> -->
{% for table in obj2 %}
<option value = "{{table}}" >{{ table }}</option>
{% endfor %}
<!-- <li>Dropdown link</li> -->
</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="return appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id ="test">
<div class="btn-group">
<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button>
<label class="control-label col-md-3">Filter</label>
<div class="col-md-4" id="filtbox">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</select>
<select class="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
<option> > </option>
<option> < </option>
<option> ≥ </option>
<option> ≤ </option>
<option> = </option>
</select>
<input class="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</input>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4" id="showquery">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" onclick="return showQuery()">Show</button>
<button id="export" class="btn btn-theme" type="Export" style="height:30px;width:100px;" onclick="return ExportFile()">Export</button>
</div>
</div>
</div>
</div>
<div id="query_result">
</div>
</form>
script to append the box
<script>
function appendBox()
{
$('#test').append('<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
return false
}
</script>
<script>
function appendFilterBox()
{
$('#filtbox').append('<select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:2px"></select><select class="operator" style="width:125px;background-color:white;height:3 0px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:3px"><option> > </option><option> < </option><option> ≥ </option><option> ≤ </option><option> = </option></select><input type="text" class="parameter" style="width:150px;background-color:white;height:30px;font-size:15px;"></input>')
return false
}
</script>
Ajax to send the data
<script>
$(document).ready(function() {
$("#result").click(function () {
var urls = "{% url 'polls:load-query' %}";
var table = $('#dataselect').val();
data = {
'name' : [],
'table': table,
'condition': []
};
$('#column-name .columnselect').each((idx, el) => data.name.push($(el).val()));
$('#filtbox .input-group').each((idx, el) => {
condition = {
'column' : $(el).find('.conditionselect').val(),
'operator' : $(el).find('.operator').val(),
'value' : $(el).find('.parameter').val()
};
data.condition.push(condition);
});
$.ajax({
url: urls,
data: data,
success: function(data) {
$("#query_result").html(data);
},
error: function(data)
{
alert("error occured");
}
});
});
});
</script>
is this the correct way to send multivalues with ajax? it seems the data didnt send properly when django want to get the data..
heres the view if you guys curious
def list_all_data(request):
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('', '', sid='') #ip port and user and password i hide it for privacy
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
c = conn.cursor()
print(request.GET.getlist('condition'))
data_name = request.GET.get('name',1)
table_name = request.GET.get('table',1)
column = request.GET.get('condition', {}).get('column', 1)
print(column)
operator = request.GET.get('condition', {}).get('operator', 1)
print(operator)
value = request.GET.get('condition', {}).get('value', 1)
print(value)
c.execute("select "+data_name+" from "+table_name+" where "+column + operator+"'"+value+"'")
c.rowfactory = makeDictFactory(c)
columnalldata = []
columnallname = []
for rowDict in c:
columnalldata.append(rowDict[data_name])
columnallname.append(data_name)
context = {
'obj4' : columnalldata,
'column_name' : columnallname
}
return render(request,'query_result.html',context)

XMLHttpRequest cannot load due to access control checks for AJAX with Django

I'm working on a project using Python(2.7) and Django(1.10) in which I'm using Ajax to make requests from Django templates and Django views.It was working perfectly well but then I have setup SSL on my server for this Django site and after I'm getting this error when making such requests:
Here's what I have done so far:
Here's my template add_category.html:
{% extends 'dashboard_base.html' %}
{% load staticfiles %}
{% block title %}
<title>Category</title>
{% endblock %}
<!-- main content -->
{% block content %}
<div class="main-content">
<div class="content-header clearfix">
<h2 class="pull-left">Add New Category</h2>
<ol class="breadcrumb pull-right">
<li><i class="fa fa-dashboard"></i> Home</li>
<li class="active">Add New Category</li>
</ol>
</div>
<div class="content">
<div class="clearfix">
<div class="content-box">
<div class="content-box-header">
<h4>Add New Category</h4>
</div>
<div class="content-box-inner">
<form class="custom-form" action="{% url 'category_add' %}" method="post" id="addcategory">
{% csrf_token %}
<div class="row">
<div class="form-group col-md-12">
<label>Category Name</label>
<input type="text" name="title" id="title" class="form-control" placeholder="Category name">
</div>
<div class="form-group col-md-12">
<label>Category Position</label>
<input type="number" name="position" id="position" class="form-control" min="1" value="1">
</div>
<div class="form-group col-sm-12">
<label>Description</label>
<textarea class="form-control" placeholder="Description" name="description" id="description" ></textarea>
</div>
<div class="form-group col-sm-12">
<label class="checkbox">
<input type="checkbox" name="enable_category" id="enable_category" class="form-control" value="1" checked="checked">
<span>Enable Category</span>
</label>
</div>
</div>
<div class="form-group">
<button type="button" id="add_category" class="btn btn-default bg-green"><i class="fa fa-floppy-o"></i>Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
<script src="{% static 'dashboard/js/jquery.min.js' %}"></script>
<script src="{% static 'dashboard/js/category.js' %}"></script>
<script type="text/javascript">
var baseurl="http://{{ request.META.HTTP_HOST }}/dashboard";
var csrf="{{csrf_token}}";
</script>
{% endblock %}
I have tried to change the baseurl in {% block js %} above from http to https, but still the same error.
And here's category.js:
$('#add_category').click(function(){
var title = $('#title').val().trim()
var description = $('#description').val().trim()
var position = $('#position').val()
var enable_category = '';
if(title.length == 0)
{
$('#title').addClass("data_is_empty");
return false;
}
if(description.length == 0)
{
$('#description').addClass("data_is_empty");
return false;
}
if(position.length == 0)
{
$('#position').addClass("data_is_empty");
return false;
}
if(parseInt(position) < 1)
{
$('#position').addClass("data_is_empty");
return false;
}
$("input:checkbox[name=enable_category]:checked").each(function(){
enable_category = $(this).val()
});
data={}
data['title'] = title;
data['description'] = description;
data['position'] =position;
data['csrfmiddlewaretoken'] = csrf;
data['enable_category'] = enable_category;
console.log('-=-=-=-=-=-=-');
console.log(data);
url=baseurl+"/category/add/";
$('.loader').css('display','block');
$(this).attr('disabled','disabled');
$.ajax({
url:url,
type:'POST',
data:data,
success:function(response)
{
var message = JSON.parse(response);
$('.loader').css('display','none');
$(this).removeAttr('disabled');
if(message.error)
{
$('#class_for_icon').removeClass('fa-check-circle')
$('#class_for_icon').addClass('fa-ban')
$('.flash_msg').css('display','block');
$('.flash_msg_text').text('Some error occur.')
window.setTimeout(function () {
$(".auto_hide").fadeTo(500, 0).slideUp(500, function () {
$('.auto_hide').css('display','none');
});
}, 2000);
// window.setTimeout(function () {
// location.reload();
// }, 2000);
}
if(message.success)
{
$('#class_for_icon').removeClass('fa-ban')
$('#class_for_icon').addClass('fa-check-circle')
$('.flash_msg').css('display','block');
$('.flash_msg_text').text('Saved Successfully')
window.setTimeout(function () {
$(".auto_hide").fadeTo(500, 0).slideUp(500, function () {
$('.auto_hide').css('display','none');
});
}, 2000);
window.setTimeout(function () {
location.reload();
}, 2000);
}
}
});
});
From views.py:
def category_add(request):
user_type = ''
try:
user_type = request.session['user_type']
except Exception as e:
pass
if user_type == 'admin':
if request.method == "POST":
title = request.POST['title']
description = request.POST['description']
position = request.POST['position']
enable_category = request.POST['enable_category']
try:
if enable_category:
obj = Categories(title=title, description=description, position=position)
obj.save()
else:
obj = Categories(title=title, description=description, enable_flag=0, position=position)
obj.save()
return HttpResponse(json.dumps({'success': 'Updated Successfully'}))
except Exception as e:
return HttpResponse(json.dumps({'error': 'Something went wrong'}))
if request.method == "GET":
return render(request, "add_category.html")
And here's the complete error I'm receiving in the browser's console:
[Error] Not allowed to request resource
send (jquery.min.js:4:26582)
ajax (jquery.min.js:4:22185)
(anonymous function) (category.js:44)
dispatch (jquery.min.js:2:41778)
[Error] XMLHttpRequest cannot load
http://www.orderfetchers.com/dashboard/category/add due to access control checks.
send (jquery.min.js:4:26582)
ajax (jquery.min.js:4:22185)
(anonymous function) (category.js:44)
dispatch (jquery.min.js:2:41778)
Note:
It's just happening after enabling SSL for my site before that it was working perfectly well.
Another Update: In chrome I see this error: Mixed Content: The page at 'https://www.orderfetchers.com/dashboard/category/add' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.orderfetchers.com/dashboard/category/add/'. This request has been blocked; the content must be served over HTTPS.
Update: Here's my apache2 configuration:
Alias /static /home/abdul/Fetchors/static
<Directory /home/abdul/Fetchors/static>
Require all granted
</Directory>
Alias /media /home/abdul/Fetchors/media
<Directory /home/abdul/Fetchors/media>
Require all granted
</Directory>
<Directory /home/abdul/Fetchors/Fetchors>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/abdul/Fetchors/Fetchors/wsgi.py
WSGIDaemonProcess django_app python-path=/home/abdul/Fetchors python-home=/home/abdul/Fetchors/venv
WSGIProcessGroup django_app
What can be wrong there?
Thanks in advance!

OctoberCms How to pass ajax response to javascript function

I created a form in my component html file, When i submit a form an ajax call triggers to my action defined in component. So far my code is working fine i'm getting response. But now i want the response to be passed to the javscript function that i created inside component htm file.
function markAddresses(addresses) {
geocoder = new google.maps.Geocoder();
addresses.forEach(address => {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({map: map,position: results[0].geometry.location});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
})
}
I want to pass my response like markAddresses(response)
<form method="post" data-request="onSend">
<div class="col-md-5">
<input type="text" name="location" class="form-control">
</div>
<div class="col-md-2">
<select name="service[]" id="services" class="form-control">
{% for client in records %}
<option value="{{ client.service }}">{{ client.service }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="area[]" id="search" class="form-control" >
{% for client in records %}
<option value="{{ client.area }}">{{ client.area }} Miles</option>
{% endfor %}
</select>
</div>
<div class="col-md-3">
<input type="submit" value="Looks for Shops" class="red-btn btn btn-default">
<a class="location-view" href="#">View all Shops</a>
</div>
This is how my Ajax is working. I think it is using octobercms Ajax framework
You can use data-attributes-api
<form method="post"
data-request="onSend"
data-request-success="markAddresses(data)"
<!-- ^-- this one -->
>
....
</form>
make sure markAddresses is global function you can access it globally. and data is return value from the handler.
If your handler looks like this
function onSend() {
return ['test' => 'data'];
}
It will pass object like below in markAddresses as variable data
console.log(data); // output : { "test": "data" }
If any doubt please comment.

Uncaught Error:cannot call methods prior to initialization;

I m calling a form in a popup using bootbox
bootbox.alert(myform, function () {
}).find("div.modal-dialog").addClass("largeWidth");
in the form there is a a pallete collor picker(evol colorpicker)
$(document).ready(function () {
$("#cd_bundle_entitiesbundle_call_Color").colorpicker();
});
The first time the form popup opens the pallete for color pick displays ok but only for one time.
After that if i close the popup and open it again when pressing for the color pick pallete getting the error
Uncaught Error: cannot call methods on colorpicker prior to initialization; attempted to call method 'hidePalette'
Reading similar questions i think i ve to destroy the bootbox popup so in the callback of bootbox tried $(this).empty or $(this).remove() but didnt work
This is my form in a html file with some js
<div class="col-lg-6">
{{ form_start(form, {'action': path('calls_edit_exec'),'attr': {'class': 'callform'} } ) }}
<fieldset>
{{ form_errors(form) }}
<div class="row">
<label class="col-md-3">Requestor</label>
<label class="input col-md-5">{{ form_widget(form.Requestor) }}</label>
<span id="inforeq" class="inforeq fade info alert-success" ></span>
</div>
<div class="row">
<label class="col-md-3">CallStatus</label>
<label class="input col-md-5">{{ form_widget(form.CallStatus) }}</label>
</div>
<div class="row">
<label class="col-md-3">Color</label>
<label class="input col-md-5">{{ form_widget(form.Color) }}</label>
</div>
<span class="fade">
<input id="mycolor" class="colorPicker evo-cp0" />
</span>
<div class="row">
<label class="col-md-3">AssignedTo</label>
<label class="input col-md-5">{{ form_widget(form.AssignedTo) }}</label>
<span id="infouser" class="infouser fade info alert-success" ></span>
</div>
<div class="row">
<label class="col-md-3">Category</label>
<label class="input col-md-5">{{ form_widget(form.CallCategory) }}</label>
<span id="infouser" class="infouser fade info alert-success" ></span>
</div>
<div class="row col-lg-12">
<div class="row">
<label class="col-md-3">Call Problem</label>
</div>
<div class="row">
<label class=" textarea col-md-12">{{ form_widget(form.CallProblem) }}</label>
</div>
<div class="row">
<label class="col-md-3">Call Solution</label>
</div>
<div class="row" >
<label class="textarea col-md-12">{{ form_widget(form.CallSolution) }}</label>
</div>
<div class=" form-control">
<input class="form" type="checkbox" name="createready" id="createready">Make this Ready Call/Solution<br>
</div>
</div>
</fieldset>
{{ form_end(form) }}
</div>
<script>
$(document).ready(function () { $("#cd_bundle_entitiesbundle_call_Color").colorpicker();
}); </script>
With a click the the form is returned from an ajax call
$.ajax({
url: url,
success: function (data) {
bootbox.alert(data, function () {
// $this.empty();
}).find("div.modal-dialog").addClass("largeWidth");
}
});
To get the form in popup i m using bootbox
I'm assuming that you're using this to load the modal with remote content:
$.ajax({
url: url,
success: function (data) {
bootbox.alert(data, function () {
// $this.empty();
}).find("div.modal-dialog").addClass("largeWidth");
}
});
If so, I would use the show.bs.modal method as the point where you trigger the colorpicker:
$.ajax({
url: url,
success: function (data) {
bootbox.alert({
message: data,
callback: function () {
// do something when dismissing the alert
},
className: 'largeWidth'
})
.on('show.bs.modal', function(){
$("#cd_bundle_entitiesbundle_call_Color").colorpicker();
});
}
});
I've also tweaked your example to use an options object, as shown in the documentation.
It's worth noting that there are size options for Bootstrap modals as of 3.1.0, which you can apply as you were with your largeWidth class, or you can use the equivalent size option as noted in the Bootbox docs I linked to previously.

jquery .click() event issue (django)

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..

Categories

Resources