changed tab value but not reflect in page? - javascript

I'm using ajax to seek a solution to dynamic update data-value in div and reflect effect in HTML.
the data-value come from the backend flask and sql DB.I know the data-value already be updated since if I refresh the page, the new data-value be reflect in page. Is there a way to achieve this function to real-time auto reflect the effect on web page ? I don't want trigger another form submit to achieve this effect. : )
In short word, the ajax response data success, but it not update the html, so web page didn't reflect the updated value.
thank you !
#app.route("/fetch_bar",methods=['POST'])
def fetch_bar():
result = [{'hostname': 'testaa101.com', 'status': '30'}] ### example data that actually getting from DB.
app_json = json.dumps(result)
return jsonify(app_json)
function bar_progress(){
$.ajax({
url:"{{ url_for('fetch_bar') }}",
type:"post",
dataType: "json",
async: false,
success:function(response){
var response = JSON.parse(response);
var len = Object.keys(response).length;
var bars = document.querySelectorAll("[id=ldBar]");
if (len > 1)
for( var ind = 0; ind < len; ind++){
if (selects[index].value == response[ind].hostname)
bars[index].setAttribute("data-value",response[ind].status);
}}})}
function shadow_progress() {
bar_progress()
setTimeout(shadow_progress, 15000);
}
shadow_progress();
<form id="myform" name="myform" action="{{url_for('show_select')}}" method="post">
{% for entry in entries %}
.....
<td>
<input id="stage" type="button" class="btn-primary" onclick="readTextFile();" name="stage" value="{{entry.stage}}" >
<div id="ldBar" class="ldBar label-center" data-value="0" data-preset="stripe" data-aspect-ratio="none" style="width:100%;display: block;" ></div>
</td>
......
{%endfor %}

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.

jquery not appending more than 20 times in ajax with django

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.

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

dynamic JQuery view in django

my jquery looks like this:
$('#id_start_date_list').change(
function get_time()
{
var value = $(this).attr('value');
alert(value);
var request = $.ajax({
url: "/getTime/",
type: "GET",
data: {start_date : value},
dataType: "json",
success: function(data) {
//Popluate combo here by unpacking the json
}
});
});
my view.py looks like this:
def getTime(request):
if request.method == "GET":
date_val = request.GET.get('start_date')
format = '%Y-%m-%d'
sd = datetime.datetime.strptime(date_val, format)
sql_qw = MeasurementTest.objects.filter(start_date = sd)
results = [{'start_time': str(date.start_time), 'id_start_time':date.start_time} for date in sql_qw]
print results
*****json_serializer = serializers.get_serializer("json")()
response_var= json_serializer.serialize(results, ensure_ascii=False, indent=2, use_natural_keys=True)*****
return HttpResponse(response_var, mimetype="application/json")
my html page looks like this:
html>
<head>
<title>date Comparison</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="/example/" method="post" align= "center">{% csrf_token %}
<table align = "center">
<tr>
<th><label for="start_date_list">Date 1:</label></th>
<th> {{ form.start_date_list }} </th>
</tr>
<tr>
<th><label for="start_time_list">time:</label></th>
<th><select name="start_time_list" id="start_time_list"></th>
<option></option>
</select>
<th></th>
<div id = "log"></div>
</tr>
<tr align = "center"><th><input type="submit" value="Submit"></th></tr>
</table>
</form>
</body>
</html>
As you can see i am getting the value from the select box and i am performing operations on the database and retreiving values and storing it in the json object.
There are two parts that i am totally blind.
First is the json object, where i am not sure whether the results are getting stored in the response_var object.
The second is that, i am not sure how to get values from a json object onto the new list of "start_time_list"
In detail: have i have done anything wrong in the json object initialisation. I have tried to print the respose_var, but it seems not to be printed on the console. Am i using the right syntax? and can someone tell me how to view the values stored in the json object in the view.py
In the similar way, how do i perform operations on the jquery side, to extract values from a json object and how to assign the values of a json object onto a list box by means of sample code and possible solutions.
To convert the results to json, use simplejson:
from django.utils import simplejson
def getTime(request):
if request.method == "GET":
date_val = request.GET.get('start_date')
format = '%Y-%m-%d'
sd = datetime.datetime.strptime(date_val, format)
sql_qw = MeasurementTest.objects.filter(start_date = sd)
results = [{'start_time': str(date.start_time), 'id_start_time':date.start_time} for date in sql_qw]
print results
response_var = simplejson.dumps(results)
return HttpResponse(response_var, mimetype="application/json")
To access the json object in your javascript, take a look at your ajax request. The success callback is being passed a parameter, data in this case. That is the variable containing the server response. So, to access the first element of the resultant array (for instance), you could:
var request = $.ajax({
url: "/getTime/",
type: "GET",
data: {start_date : value},
dataType: "json",
success: function(data) {
//Popluate combo here by unpacking the json
data[0]; // This is the first element of the array sent by the server
}
});
Lastly, to modify the html, jQuery provides plenty of methods, such as html or append. It's worth taking a look at the doc. So if you want to build a collection of options for a select tag, you should iterate over the result set using the javascript for loop, jQuery each method or similar, construct the options (this can be accomplished either concatenating strings or creating DOM elements, which I think is the best solution, as it performs better) and insert them in the html with one of the methods previously mentioned.

Categories

Resources