jquery not appending more than 20 times in ajax with django - javascript

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.

Related

Update single row of table in template page using ajax in Django

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.

Django jquery AJAX form submission in view and display results

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

load part of the html page when filtering results with ajax

I want to filter a search results using 3 checkboxs. The results are presented in the div with the id=posts_results
<div class="checkbox">
<label><input type="checkbox" id="id1" class="typePost" value="En groupe"> val1 </label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="id2" class="typePost" value="En groupe"> val2 </label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="id3" class="typePost" value="A domicile"> val3</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4</label>
</div>
<div id="posts_results">
{% include 'posts/posts_results.html' %}
</div>
<script>
$('.typePost').change(function (request, response) {
var v1=$('#id1').is(":checked")? 1:0;
var V2=$('#id2').is(":checked")? 1:0;
var V3=$('#id3').is(":checked")? 1:0;
var v4=$('#id4').is(":checked")? 1:0;
$.ajax({
url: '/posts/type_lesson/',
dataType: 'json',
type: "GET",
data: {
group: groupChecked,
webcam: webcamChecked,
home: homeChecked,
move: moveChecked,
distance: distance,
},
success: function (object_list) {
$('#posts_results').load("my_page.html", object_list);
alert('after')
}
});
});
<script>
this is my url:
url(r'^filter/$', views.filter, name='filter_type_lesson'),
and this is my view:
def filter(request):
if request.method=='GET':
#as an exemple I'll send all posts
data= PostFullSerializer(Post.objects.all(), many=True)
return JsonResponse(data.data, safe=False)
The filter function excute some filters according to the json sent data, serialize the filtered posts and send them back (in this case I send all the posts as an example).
The results are displayed using a forloop in the div with id "posts_results" and the html is in the file posts_results.html.
The json data are sent but the ajax success function does not update or load the div
and it is also possible to stay
I like to stay away from raw POST data as much as possible and let the forms API do the heavy lifting. You can do what you have already with a lot less code in a much more secure way.
Make a form with four BooleanFields named for the BooleanFields in your model. You can override how they are displayed in the HTML with the label variable.
class TheForm(forms.Form):
my_field = forms.BooleanField(required=False, label="What I want it to say")
my_field2 = forms.BooleanField(required=False, label="What I want it to say 2", help_text="Something else")
my_field3 = forms.BooleanField(required=False, label="What I want it to say 3", help_text="Something else")
Output as <form class="my_form">{% csrf_token %}{{form.as_table}}</form>
Submit it with JS like this:
$('.my_form input[type=checkbox]').change(function(e){
e.preventDefault()
$.post('module/filer/', $('.my_form').serialize(), function(data) {
// Handle data
});
});
When the form is submitted and validated take the cleaned_data attribute and filter your models like this
models = Post.objets.filter(**form.cleaned_data)
This will work because the form fields and named the same as the fields in your model. The same as doing Post.objects.filter(my_field=True, my_field2=True, my_field3=False). Then you can do whatever you want with it. I would use a FormView to do all this:
class MyView(FormView):
form_class = TheForm
def form_valid(self, form):
models = Post.objets.filter(**form.cleaned_data)
data= PostFullSerializer(data, many=True)
return JsonResponse(data.data, safe=False)
Now nothing is going to update the div by itself. It is only created when the HTML is initially requested. In your success function you'll need to append your elements manually like this:
$('.my_form input[type=checkbox]').change(function(e){
e.preventDefault()
$.post('module/filer/', $('.my_form').serialize(), function(data) {
var post_results = $('#post_results').html(''); // Clear out old html
$.each(data, function(item) {
// Create new divs from ajax data and append it to main div
var div = $('<div>');
div.append($('<div>').html(item.my_field));
div.append($('<div>').html(item.my_field2).addClass('something'));
div.appendTo(post_results);
});
});
});
You can also just past rendered HTML through ajax and do $('#post_results').html(data);. Instead of calling json response you would call self.render_to_response on the FormView.
maybe you could try to render the template in your view and then load the rendered data in your div.
Supposing your posts/posts_results.html is some as:
<ul>
{% for post in posts %}
<li> Post: {{post.name }} / Author: {{post.author}} / Date: {{post.created_at}}</li>
{% endid %}
<ul>
In your view, at the moment when you do respective actions, you can render the template and add the html content to the response, ie (based un your current code):
def filter(request):
if request.method=='GET':
json_data = {
"success": False,
"message": "Some message",
"result": "some result",
}
posts = Post.object.all()
template = "posts/posts_results.html"
things_to_render_in_your_template = {
"posts": posts, # you can add other objects that you need to render in your template
}
my_html = get_template(template)
html_content = my_html.render(things_to_render_in_your_template)
# here the html content rendered is added to your response
json_data["html_content"] = html_content
json_data["success"] = True
return JsonResponse(json_data)
Then in your JS, at the momento to check ajsx response, you can add the rendered content into your div
$.ajax({
url: '/posts/type_lesson/',
dataType: 'json',
type: "GET",
data: {
group: groupChecked,
webcam: webcamChecked,
home: homeChecked,
move: moveChecked,
distance: distance,
},
success: function (response) {
# response is the json returned from the view, each key defined in your json_data dict in the view, is a key here too
# now insert the rendered content in the div
$('#posts_results').html(response["html_content"]);
alert('after');
}
});
I suggest you instead of create one by one data to your ajax request, use serialize method of jquery or create a FormData object, also instead of GET, use POST to do your request more safe

Django, jQuery. I can't load() after the same div multiple times

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

Get HTML component from which button was pressed

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>

Categories

Resources