I am trying to let the user create multiple types of the same input form.
The problem is that the first time I click on the button a form is appended to the append_form div, but no matter how many more times I click on the "Add" button, no other form is appended. What am I doing wrong?
This is my HTML code:
<div class="col-md-9"><strong>{% trans "Please, add as many measures as you like to be available for the institutional simulation" %}</strong></div>
<div class="col-md-3"><button class="btn btn-success" onclick="addForm('{% url "add_measure_form" %}')"><i class="fa fa-plus-square"></i> {% trans "Add Measure" %} </button></div>
<div id="append_forms"></div>
And this is my script
function addForm(url){
$("#append_forms").after().load(url);
}
And this is my django views:
def add_measure_form(request):
data = {
}
return render(request, "_frm_inner_form.html", data)
and urls
url(r'^measures/form/add/$', add_measure_form, name="add_measure_form")
remove the after() function append a wrapper div to the forms and load the data into it:
function addForm(url){
$("#append_forms").append('<div>').load(url);
}
or use the general ajax request
$.ajax({
url:url,
success:function(data) {
$("#append_forms").append(data);
}
});
Related
I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details:
table name = demo
id int primary key NOT NULL,
stat_id int(11) NOT NULL #value is 1
Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button.
status.html:
<td>
<form action = "/modules" method="get">
{% if status == 1 %}
{% csrf_token %}
<button link="submit" class="btn btn-default btn-sm">
<span class="badge badge-dot mr-4">
<i class="bg-success"></i>Completed</button>
</form>
{% else %}
<button type="button" class="btn btn-default btn-sm">
<span class="badge badge-dot mr-4">
<i class="bg-warning"></i>Running</button>
{% endif %}
views.py:
def process(request):
hash_id = request.session.get('hash_id')
print(hash_id)
check = request.session.pop('check_status',)
if hash_id and check:
stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first()
if stat:
stat = stat.stat_id
print(stat)
return render(request, 'enroll/status.html', {'status': stat})
urls.py:
path('status', views.process, name='process')
models.py:
class status_mod(models.Model):
id = models.BigIntegerField(primary_key=True)
stat_id = models.BigIntegerField()
class Meta:
db_table = "demo"
jquery / ajax in my status.html page:
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: "{% url 'process' %}",
success: function(response){
console.log(response)
},
error: function(response){
alert("NO DATA FOUND")
}
});
}, 2500);
});
</script>
Now, I want to update my table row as situation will be if status == 1 then completed button will display else running. Hence it is working fine without ajax but I have to refresh again and again when process function is executed. So, I want to use ajax in this case to update the table row automatically without reloading it.
i am working on blog project, when i click submit post would be created and ajax will live reload the page. its working as i expected but as soon as my post reaches 20 it would stop appending to that perticular div, but the model object is being created correctly,when i go to admin there would 25,35 or 50 model object but only first 20 would be appended?
ajax
$(document).ready(function(){
// $("button").click(function() {
// $("html, body").animate({
// scrollTop: $('html, body').get(0).scrollHeight
// }, 2000);
// });
$(document).on('submit','#post_form',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:"{% url 'create' %}",
data:{
message: $('#message').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success:function(){
}
});
});
setInterval(function(){
$.ajax({
type:'GET',
url:"{% url 'comments' %}",
success:function(response){
$('.display').empty();
for(var key in response.comments){
if (response.comments[key].name != '{{request.user}}'){
var temp = "<div class='message_area'><p id = 'author'>"+response.comments[key].name+"</p><p id='messagetext'>"+response.comments[key].message+"</p></div><br>"
$(".display").append(temp);
}
if (response.comments[key].name == '{{request.user}}'){
var user_temp = "<div class='message_area_owner'><p id='messagetext_owner'>"+response.comments[key].message+"</p></div><br><br><br>"
$(".display").append(user_temp);
}
}
},
error:function(response){
console.log("no data found")
}
});
}, 500);
});
html
{% if request.user.is_authenticated %}
<div class="display"></div>
<div class="input">
<form id="post_form">
{% csrf_token %}
<input type="text" id="message" name = 'message' autocomplete="off" onfocus="this.value=''">
<button type="submit" id="submit" onclick="scroll()">SENT</button>
</form>
</div>
{%else%}
<a class="btn btn-danger" href="{% url 'login' %}" style="text-align: center;">login</a>
<a class="btn btn-danger" href="{% url 'register' %}" style="text-align: center;">register</a>
{% endif%}
views and models as normal
when i press post btn model object is getting created but not appending to .display div if it has already 20 divs in that
actually my question is why you want to get all comments via ajax? the object has some comments available when user requested the page, so you could render that available ones to the template. and just use ajax to get the new one that user may add. the last one and also it's easier to get this last one in the success method of ajax itself when comment has been sent and if it was successfully added to database. also you may need append function in javascript to append the response to the dom. and use render_to_response in the django part so to render a pace of template which contains the comment box(some magic use component like a frontend framework) and then append that pace of rendred html to the dom.
There are a lot of different posts about all parts of this, I just can't quite figure out how it all fits together.
I have name that is displayed with an update button next to it. When the update button is clicked it shows a form to update the name. In the form is a save changes button. When the changes are saved, it should reload the name at the top, and should the update button be clicked again, the form should show the new name info.
urls.py
path('profile/<int:pk>/', views.customer_profile, name='profile'),
path('update-profile/<int:pk>/', views.update_profile, name='update-profile'),
views.py
def customer_profile(request, pk):
name = get_object_or_404(CEName, id=pk)
name_form = NameForm(instance=name)
return render(
request,
'customer/customer_profile.html',
{'name':name, 'NameForm': name_form}
)
def update_profile(request, pk):
if request.POST:
name_form = NameForm(request.POST)
if name_form.is_valid():
name_form.save()
name = get_object_or_404(CEName, id=pk)
context = {'name':name, 'NameForm': name_form}
html = render_to_string('customer/customer_profile.html', context)
return HttpResponse(html, content_type="application/json")
template.html
<div id="name" class="container d-flex justify-content-between pt-1">
{{ name }}
<button id="update_button" class="bold btn btn-main btn-sm button-main">UPDATE</button>
</div>
<div id="div_NameForm" class="container" style="display: none;">
<hr size="3px">
<form id="NameForm" method="POST" data-url-name="{% url 'customer:update-profile' name.id %}">
{% csrf_token %}
{{ NameForm.as_p }}
<br>
<button type="submit" id="save_changes" class="btn btn-main button-main btn-block">Save Changes</button>
</form>
</div>
<script src="{% static 'ce_profiles/ce_profiles_jquery.js' %}"></script>
jquery.js
$('#save_changes').click(function() {
var NameForm = $('#NameForm');
$.ajax({
type: 'post',
url: NameForm.attr('data-url-name'),
data: NameForm.serialize(),
dataType: 'json',
success: function(data, textStatus, jqXHR) {
$('#name').html(data);
}
});
});
The code for the update button toggle is not displayed.
In your jQuery, to start with.
- First, you could (some may say should) have put a submit event handler on the on the form instead of a click event for button.
- Second, you are doing an AJAX call so you should prevent form submission using .preventDefault() on the submit event that was trigged when the button was pressed. This will prevent the page from reloading.
- Third, in your ajax success callback you should use text() instead of html() since name I imagine is text and not html, however that's just an assumption.
$('#NameForm').on('submit', function(evt) {
evt.preventDefault();
var NameForm = $('#NameForm');
$.ajax({
...
success: function(response) {
$(#name).text(response); // or response.name or whatever
}
});
})
How do I get the HTML component that contains the button which has been clicked with jQuery? After a button is clicked I need to get the invite object that corresponds to the clicked button and send a post request to a given link.
{% if invites %}
{% for invite in invites %}
<p>Your invites:</p>
<div class="row">
<label style="display: block">Invite from {{ invite.initiator }} to join his conference!</label>
<button type="button" id="ButtonId">Accept invite</button>
</div>
{% endfor %}
{% endif %}
The script:
<script type="text/javascript">
$(function() {
$('#ButtonId').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
$('#ButtonId').val('Done');
var data = {
};
$.ajax({
url: '/api/send_invite/' + /*the username*/,
data: JSON.stringify(data , null, '\t'),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function() {
}
});
});
});
</script>
Your "HTML component" is what the button is wrapped in ? If so, In order to get the element that contains the button that is being clicked (the "parent" of the button) you can do something like this:
$('#myButton').on('click',function(){
var buttonParent = $(this).parent();
// do your stuff..
});
For getting the "invite object" you can attach a data attribute to the accept-invite button, this data attribute will contain a value that you will use to fetch the correct object, for an example:
<button type="button" id="inviteAcceptBtn" data-object-id="123">Accept invite</button>
Then you can get that "object-id" with simple jQuery:
$('#inviteAcceptBtn').on('click',function(){
var objectId = $(this).data('object-id');
// do your stuff..
});
There are probably a handful of other methods, as there are many techniques to do this.
Hope it helps a bit
There are multiple ways to do this:
Set the the username as one of the button's attributes.
assuming invite.initiator is the username that you intend to send
<button type="button" id="ButtonId" username={{invite.initiator}}>Accept invite</button>
In the javascript code you can access that element easily using attr method on this
url: '/api/send_invite/' + $( this ).attr("username"),
#sudomakeinstall2 : It should be better to add the data as a data-attrbute so :
<button type="button" id="ButtonId" username={{invite.initiator}}>Accept invite</button>
becomes
<button type="button" id="ButtonId" data-username="{{invite.initiator}}">Accept invite</button>
I use the following approach for handling modal window: check article here https://dmorgan.info/posts/django-views-bootstrap-modals/
But I don't understand how to implement some trivial functionality using such approach
Inside my html I have such thing:
{% for order in queryset%}
<tr>
** some order data here **
<td></td>
<div class="text-center">
<input type="hidden"/>
<a
id="make-offer-button"
role="button"
title="Make offer"
class="btn btn-inverse" data-toggle="modal">
<i class="icon-plus"></i>
</a>
</div>
</td>
</tr>
{% endfor %}
When I click to make-offer-button modal window must appear with particular object. But modal window loads only for the first record in the table, it doesn't work for the second, third, etc., records.
Also I have a great doubt, that modal window has any relation to particular object.
How can I relate particular object with modal window?
JS:
var formAjaxSubmit = function(form, modal) {
$(form).submit(function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (xhr, ajaxOptions, thrownError) {
if ( $(xhr).find('.has-error').length > 0 ) {
$(modal).find('.modal-body').html(xhr);
formAjaxSubmit(form, modal);
} else {
$(modal).modal('toggle');
window.location.replace('http://127.0.0.1:8000/my_orders/');
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
}
$('#create-order-button').click(function() {
$('#form-modal-body').load('add_order_form/', function () {
$('#form-modal').modal('toggle');
formAjaxSubmit('#form-modal-body form', '#form-modal');
});
});
$('#make-offer-button').click(function() {
$('#form-modal-body').load('make_offer_form/', function () {
$('#form-modal').modal('toggle');
formAjaxSubmit('#form-modal-body form', '#form-modal');
});
});
views.py
class AjaxTemplateMixin(object):
def dispatch(self, request, *args, **kwargs):
if not hasattr(self, 'ajax_template_name'):
split = self.template_name.split('.html')
split[-1] = '_inner'
split.append('.html')
self.ajax_template_name = ''.join(split)
if request.is_ajax():
self.template_name = self.ajax_template_name
return super(AjaxTemplateMixin, self).dispatch(request, *args, **kwargs)
class MakeOfferView(SuccessMessageMixin, AjaxTemplateMixin, FormView, CreateView):
model = ExchangeTransaction
template_name = 'make_offer_form.html'
form_class = ExchangeTransactionForm
success_url = reverse_lazy('all_orders')
success_message = "Way to go!"
def form_valid(self, form):
transaction = form.save(commit=False)
transaction.user = self.request.user
transaction.order = form.order
transaction.save()
return redirect('currency_exchange.views.all_orders')
HTML id attributes must be unique; you have used the same value for each button. Use a class instead.
In the for loop, you are creating the <a> fields with same id (same id's are not allowed). Use class instead, and add action listener to the class.
For your next query, suppose you have a modal code written, and you want it to have different attributes for different objects/items in your html. Handle it using javascript. For a click event on your current object, get the properties of your clicked object, and set it to corresponding attributes in your modal.
When I make modals in a loop, I append the object's id (or something unique to the object) to the button's data-toggle and the modal's id.
For example, your button's data-toggle:
{% for order in queryset%}
...
<a class="btn btn-inverse" data-toggle="modal-{{ order.id }}">
...
{% endfor %}
Then be sure to do the same for your modal:
<div class="modal" id="modal-{{ order.id }}">
...
</div>