How to use Flask Jinja Template generated content and JQuery Ajax functionality? - javascript

I am creating an app with Flask and JQuery which accepts input from user like this
<form>
{% for i in range(length) %}
<div class="form-group has-success has-feedback">
<label for="question">Question {{ i+1 }}: {{ qlist[i] }}</label>
<textarea class="form-control" rows="5" id="CAT_Custom_{{ i+1 }}" name="CAT_Custom_{{ i }}"></textarea>
<span class="glyphicon glyphicon-ok form-control-feedback"></span>
</div>
{% endfor %}
<input type="submit" name="submit" class="submit action-button" value="Submit" />
</form>
here qlist is a list of questions like this
['What is a Network?', 'What is a Router', ...]
Before submitting the form I want to make sure that each question has an answer of at-least 100 words typed by user. So I'm trying to use a function called process which returns error or success based on the length of answer.
#app.route("/process", methods=["POST"])
def process():
name = request.form['name']
if len(name.split()) >= 100:
return jsonify({'success' : name})
return jsonify({'error': 'No data'})
Now the problem is since my form inputs are dynamically created how do I check if every individual answer is of length 100 words or above.
My attempt was like this but it changes every textarea inputs not just the one with less number of words.
$(function() {
$('form').on('submit', function() {
$.ajax({
data : {
name : $(this).find('.form-control').val()
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if(data.error) {
$('.form-group').find('span').removeClass('glyphicon-ok').addClass('glyphicon-remove');
} else {
$('.form-group').find('span').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
});
event.preventDefault();
});
});

I found a solution to my problem like this
$(function() {
$('.form-group').focusout( function(event) {
var target = $(this);
$('.form-group').each(function() {
var target = $(this);
$.ajax({
data : {
name : target.find('.form-control').val()
},
type : 'POST',
url : '/process'
}) // Ajax close
.done(function(data) {
if(data.error) {
target.find('span').removeClass('glyphicon-ok').addClass('glyphicon-remove');
} else {
target.find('span').removeClass('glyphicon-remove').addClass('glyphicon-ok');
} // if close
}); // done close
event.preventDefault();
}); // each close
});
});

Related

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.

how to get id of textbox typeahead

I've dynamic textbox list with different id and also apply typeahead JavaScript to add functionality of tag and auto search with ajax. But I want to get id of textbox in which I'm typing, means there are 3 textboxes with id txtid1, txtid2 & txtid3 are there and I'm writing in txtid2 then I want this id everytime when my keyup event is call.
Can anyone suggest me what to do and I also want to know that how to get Id from all tag means 3 tag with value CAR, Truck & Plan with id 1, 2 & 3 so #time of submit I want 1,2,3 with tag manager
$('.typeahead').on('keyup', function () {
var catid = '';
var tagApi = $(".tm-input").tagsManager();
jQuery(".typeahead").typeahead({
name: 'tags',
displayKey: 'name',
source: function (query, process) {
var id = $(this).attr('id');
var category = id;
console.log('ud='+$(this).attr('id'));
return $.get('ajax.php', {query: query, gettag: 'gettag', catid: category}, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
afterSelect: function (item) {
tagApi.tagsManager("pushTag", item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="controls">
<input name="tags" placeholder="Tags" class="typeahead tm-input form-control tm-input-info" id="setattr2" data-original-title="" title="" type="text">
<input name="hidden-tags" type="hidden">
</div>

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>

Django - Dictionary of Forms

I'm trying to implement a dictionary of forms where two fills are initialized with some values I have. I'm passing this through a Jquery function but when its going to add it to the template, the jquery function has an error that says Cannot set property 'value' of null when trying to execute this document.getElementById('example1').value = example;
My code here:
view.py
def exampleCaesar(request):
if request.is_ajax() and request.method == "GET":
form = caesarCipher(request.GET or None)
if form.is_valid:
wordToEncrypt = request.GET.get('word')
wordToEncrypt = wordToEncrypt.upper()
wordLength = len(request.GET.get('word'))
key = request.GET.get('the_key')
print(wordLength)
print(key)
equations = {}
for x in range(wordLength):
exampleForm = caesarCipher(initial={'letterOfWord' : wordToEncrypt[x], 'key' : key})
##print(exampleForm)
if exampleForm.is_valid:
equations = (exampleForm)
print(equations)
context = { 'equations' : equations
}
return render(request, "content/exampleCaesar.html", context)
Javascript file
$("#encryptButton").on({
click : function() {
var variable = document.getElementById('id_plaintext');
console.log(variable.value)
$.ajax( {
url: "/exampleCaesar",
type : "GET",
data: { CSRF: 'csrf_token',
word: $('#id_plaintext').val(),
the_key: $('#id_key').val()
},
success : function(example) {
$('#example1').show();
$('#example1').html(example);
document.getElementById('example1').value = example;
console.log(example);
}
}); //END OF Ajax
} //END OF FUNCTION
}); //END OF encryptButton
Template file
{% for letterOfWord, key in equations.items %}
<form onsubmit="return false;" method="GET" class="exaSubmit" enctype="multipart/form-data">
{% csrf_token %}
<div id="example1" type="hidden">
( {{ letterOfWord }} + {{ keyToUse }} ) MOD 26 =
{{ letterToFill }} <button name="action" class="validateButton" value="validate"> Validate </button> <br>
</div>
</form>
{% endfor %}
I believe I'm not filling the dictionary the right way. When I try to print it out in the console to see the values, only the names of the fields are but not the values. My bets are in this section but not entirely sure how's that possible when I'm appending the information to it.

how to send data with ajax using ckeditore?

I have a form in django. it's 'composing mail' form. I send this form from view to my template and i apply ckeditor to chang the body style. i want this form to be posted by ajax. and when ckeditor is used, value of body field isn't send with request.POST. i use this line of code to use ckeditor:
CKEDITOR.replace('id_body');
(without using ckeditor, every thing works fine.)
<form id="compose_form" action="compose/" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div>
<div class="form-field">
<label for="id_recipient">{% trans 'recipient' %}:</label>
{{ form.recipient }}
{{ form.recipient.errors }}
</div>
<div class="form-field">
<label for="id_subject">{% trans 'subject' %}:</label>
{{ form.subject }}
{{ form.subject.errors }}
</div>
</div>
<div class="form-field">
{{ form.body }}
{{ form.body.errors }}
</div>
<input id="messages-submit" type="submit" value=""Send"/>
</div>
</form>
and i use this script to send form data via ajax:
<script type="text/javascript">
$(function() {
$('#compose_form').submit(function() {
var temp = $("#compose_form").serialize();
$.ajax({
type: "POST",
data: temp,
url: 'compose/',
success: function(data) {
// do s.th
}
});
return false;
});
});
</script>
with this script, body value isn't send to request.POST(i mean it sends empty string in body field), when i add the below line to my script, it sends value of body field, but it isn't ajax any more. Can you please help me what to do?
The reason that the data in the editor isn't included in the form is because the editor isn't a part of the form. It needs to update the form element you have associated it with. For this to happen you need to tell the editor to update the form element.
So in the submit function for your form you need to grab data from the editor.
This should do the trick:
$(function() {
$('#compose_form').submit(function() {
for (var instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
var temp = $("#compose_form").serialize();
etc etc...
I also had the same issue with django-ckeditor,What I tried is
<script type="text/javascript">
for (var instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
then checked the instance name by:
console.log(instance)
it gave "id_Your_Message" ,,So I did:
var temp = $("#id_Your_Message").val()
it works fine
<script type="text/javascript">
$(function () {
$('#submit_button_id').click(function () {
$.post("action post file url", $("#form_id").serialize(), function (data) {});
});
});
</script>
I hope above script may be help you

Categories

Resources