Confirmation on list item click then follow href - javascript

I'm currently using Django in my template to generate href for each list element and on the url, a certain method is executed, removing the item from the list, however I'd like a confirmation box to appear to assure the user they wish to delete it.
The only issue is the url is dynamic, and changes for each element of the list using django variables, shown below:
<div id="list5">
<ul>
{% if results %}
{% for result in results %}
<li><strong>{{result.0}}</strong>evaluating {{result.1}}</li>
{% endfor %}
{% else %}
<li><strong>Assessor</strong>evaluating Assessee</li>
{% endif %}
As a result, inline javascript onclick methods, and JQuery that I've been able to find on stack overflow doesn't seem to be working for me, is there a way I can generate a confirmation box (browser confirm is fine) on clicking of the list element, which then on a "yes" redirects and follows the url from the list element that the click was made from?

You should be able to use a setup like this:
jQuery:
$(document).ready(function() {
$('.deleter').click(function() {
if(confirm('Are you sure you want to delete this?') == true) {
window.open($(this).attr('goto'));
}
})
})
Template:
<div id="list5">
<ul>
{% if results %}
{% for result in results %}
<li class='deleter' goto='/accounts/delete/{{result.0}}/{{result.1}}'><strong>{{result.0}}</strong>evaluating {{result.1}}</li>
{% endfor %}
{% else %}
<li><strong>Assessor</strong>evaluating Assessee</li>
</ul>
{% endif %}
</div>

Related

How to associate dynamic value with HTML elements?

I want to create a list which is clickable and which would allow me to take a survey when I click it.
{% extends "layout.html" %}
{% block title %}
Take Survey
{% endblock %}
{% block main %}
<div class="list-group">
{ for search in searches }
{{search.topic}}
{ endfor }
</div>
{% endblock %}
When I click it I want it to go to a page which shows the questions of the survey whose topic was being shown.
I have created SQL tables for users,surveys,questions and options. Surveys are linked to users, questions are linked to surveys and options are linked to questions.
I just need a way to access the survey id({{search.id}}) in my take route where I could run a SQL query using the survey id to link everything.
Just a disclaimer, I am a beginner in HTML so please try to explain elaborately.
There are multiple ways that you can do this with html, here are a few of them
create a hidden input with the value that u need, and later when u need it retrieve it from that input
<input type="hidden" id="searchId" name="searchId" value="3487">
add a custom attribute to an element, and later when needed retrieve it from that element
<div class="list-group">
{ for search in searches }
{{search.topic}} data-search-id="{{search.id}}"
{ endfor }
</div>
There are also multiple ways you can do this without html
insert a script that has the search id, and later retrieve that id from javascript
{% block main %}
<div class="list-group">
{ for search in searches }
{{search.topic}}
{ endfor }
<script>
// just make sure that this variable is unique, so u dont cause errors or overwrite another variable by mistake
const MY_APP_SEARCH_ID ={{search.id}}
</script>
</div>
{% endblock %}
You could also generate a unique url for each survey
{{search.topic}}
and then handle that search id from the \take endpoint

django jquery scrolling does not activate

I have a jquery function that works when I run that as an event, but does not work when I try to get it to run when the document reloads.
This is my element for the window to scroll to when the page refreshes.
{% block content %}
{% for poll in polls %}
<button class="test" id="{{ poll.id }}">{{ poll.id }}</button>
{% endfor %}
{% endblock %}
This code below works fine, it's attached to a click event.
{% block jquery %}
{# <script>#}
testEvent();
// sending the poll id to report after the flag is clicked on
function testEvent() {
$(".test").click(function(event){
event.preventDefault();
var scrolltoid = document.getElementById('54')
scrolltoid.scrollIntoView(true);
window.scrollBy(0, -50);
});
};
{# </script>#}
{% endblock %}
I need the code to work when the page refreshes. However, when the same code is inserted into document ready function to scroll the window to the specific element when the page refreshes, it is not working.
{% block jquery %}
{# <script>#}
$(document).ready(function(){
var scrolltoid = document.getElementById('54')
scrolltoid.scrollIntoView(false);
})
{# </script>#}
{% endblock %}
I also tried running the alternative code below. I saw the scroll successful very quickly for just a split second, but when the page completely refreshes, my window scrolls back to the top again instead of shifting to the element id.
{% block jquery %}
{# <script>#}
$(document).ready(function () {
// Handler for .ready() called.
$('html, body').animate({
scrollTop: $('#54').offset().top
}, 'slow');
});
{# </script>#}
{% endblock %}
This code was left over by a previous programmer and I am confused about the usage of {# #}. I think the reason my code wouldnt work might be because of the {# #} that was included. I am very confused as to its usage, if I remove the comment, all the jquery/javascript on the page would stop running, so I couldn't remove it. But this confuses me because {# #} is for commenting out code on django, and what is commented out should not impact the code itself, but the {# #} tag in my code is required to get all the script on my page to work (except it doesn't work with scroll when page refreshes). I have tried doing research on {# #} but havent found anything useful on it.

jquery id is matched but won't work at all

I have python/django app, need search engine and for search engine I'm using the power of jquery. I'm still very new to Jquery(actually whole Javascript) but I think this seems right to, I'm not sure why this won't work.
so I have this code:
<li class="nav-header">search for community</li>
{% csrf_token %}
<input type="text" id="search" name="search" />
<ul id="search-results">
</ul>
I have input id search. and another id search-results.
then I have this javascript file.
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});();
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
I'm matching id search here. using keyup function. Is it because the function is wrong?It's very unlikely because the whole thing works fine. by whole thing , I mean the functionality of searching works here http://127.0.0.1:8000/search/ which has search.html
{% extends 'base.html' %}
{% block content %}
<h2>Search</h2>
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
{{ result.object.name }}
</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}{% endif %}« Previous{% if page.has_previous %}{% endif %}
|
{% if page.has_next %}{% endif %}Next »{% if page.has_next %}{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{%endblock%}
I'm trying to use what works in search.html to work in a search bar in index.html and with Jquery keyup function.
can you please tell why I can't use jquery function that has matched id?
For detail: this is how my code works
Inside urls.py
I have url(r'^search/$',include('haystack.urls')),
and other haystack settings.
then inside views.py
def search_titles(request):
categories = SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text', ''))
return render_to_response('ajax_search.html', {'categories' : categories
})
for ajax_search.html
{% if categories.count > 0 %}
{% for category in categories %}
<li>{{ category.title }}</li>
{% endfor %}
{% else %}
<li>None to show!</li>
{% endif %}
The problem is occuring from ajax I'm almost sure
If you're just practicing AJAX, your approach is ok, but jQuery has a neat method to do this..
$(function(){
$('#search').keyup(function() {
$('#search-results').load("/search/", {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
});
});
});
Have you checked in developer tools(chrome)? If you go to Network tab, then click on XHR, you will get all the ajax requests for the current page.
Now, when you find your request, click it and go to "Response". If HTTP code 20x or 304 is used, you're getting a proper response back. If not, the server doesn't know how to handle your request(404) or a server error occured(500).
If you're getting a proper response back, try adding a console.log inside that callback. You should see whatever your script is returning.
Ajax is never to blame, ajax is just the method for hiding client > server communication. It's either how the client side script is handling things or how the server side script is handling things.
I saw this hasn't been resolved yet.
The way I usually do this is by setting the global site root just before loading the JS file or by generating an url for your search url. Then in your javascript file, just use the global variable that you set earlier. I don't know django so code below could have errors.
<script type='text/javascript'>var ROOT= {{ build_absolute_uri('/')|escapejs }};</script>
<script src='{% url search_script %}'></script>

Django template ifequal statement always true

Hi I am building a simple blog using Python/Django. In my index.html file, I am trying to show archived posts when a button containing a month is clicked. At the moment, I am just trying to get the id of every post made in that month into a javascript array. For some reason though,it always returns true!
<script type="text/javascript">
function showPosts(month)
{
var posts_in_month=[];
{% for post in all_posts %}
var match = {{ post.pub_date.month }}
{% ifequal match month %}
posts_in_month.push({{ post.id }})
{% endifequal %}
{% endfor %}
}
</script>
I then go on to have a switch statement where I show the contents of the array depending on the month clicked. The code definitely works, when I call an alert(month) it shows up correctly, and when I call alert({{ post.pub_date.month }}) it shows up fine as well. These are usually not the same though, why is it always evaluating the ifequal to true?
You cannot create Javascript variable in python and use it as python's variable.
Replace the match with actual value:
{% ifequal post.pub_date.month month %}
posts_in_month.push({{ post.id }})
{% endifequal %}

Django make the passed data invisable from view source

I pass some data and process in my django template file. It works just fine. However, when i right click and then select "view page source" on my internet browser, i can see all the values that i passed from my view.py. How to hide the values in the template file.
Child.page
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block extra_js %}
<script>
var secret_data = new Array();
function mybutton(){
{% for data in Mysecret%}
// Here, I wanna make the value of data invisable
secret_data.push({{ data.0 }})
{% endfor %}
}
</script>
{% endblock %}
{% block content %}
<input type="submit" name="submitButton" value="Submit" onclick ="mybutton();"> </input>
{% endblock %}
When i right click and select "view to source" on my internet browser, i can see all the values something like that:
<script>
var secret_data = new Array();
function mybutton(){
secret_data.push("Secret-1")
secret_data.push("Secret-2")
}
</script>
I have tried this:
secret_data.push({% csrf_token %}{{ data.0 }})
The values cannot be seen in case of viewing source code of the page, but at the same time it messes up the data that i pass (cannot access data cause the data turns out a div). How can i make my secret_data list invisible so that if someone tries to view source of my page, she would not be able to see the passed values ("Secret-1" and "Secret-2").

Categories