Undesired text is added when setting the href attribute with JavaScript - javascript

I am developing on localhost: http://127.0.0.1:8000
When I perform some search on the website, I want that if the query does not return results, the New entry button allows the creation of a new article from what has been searched in the search input.
So if I search 'whatever' and there is no article called 'whatever', the button should redirect me to the creation page of the article 'whatever'.
<script>
$( document ).ready(function() {
var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}";
document.getElementById('newEntrybtn').setAttribute('href',newEntryUrl);
});
</script>
{% for article in articles %}
{% block wiki_search_loop2 %}
{% endblock %}
{% empty%}
There is no page created for '{{ search_query }}', would you like to create a page nowee?
<a class="btn btn-success" id="newEntrybtn" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a>
{% endfor %}
To calculate the url to create the new article, I use this line:
var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}";
If I do an alert(newEntryUrl); it returns the desired result: 127.0.0.1:8000/wiki/_create/?slug=whatever
However, if I click the newEntrybtn button, it redirects me to the following url: http://127.0.0.1:8000/wiki/_search/127.0.0.1:8000/wiki/_create/?slug=whatever
Which is strange to me since at no time have I assigned the href attribute to the button, much less have I assigned it any value. It seems that somehow, by default, it gets the value of the current page.
My question is, how can I remove the current page: http://127.0.0.1:8000/wiki/_search/ so that the button href just has this structure: 127.0.0.1:8000/wiki/_create/?slug=whatever ?

I think you are appending the value twice. Once when the page loads because it is in the document.ready function and once again when the button is clicked. Try writing it in another function and calling the function when the button is clicked.
setAttribute is being called twice
https://codepen.io/sijbc/pen/zYNdrmz
.setAttribute() is being called twice
function createUrl(){
var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}";
var newEntryBtn = document.getElementById('newEntrybtn')
newEntryBtn.addEventListener("click" function(){
newEntryBtn.setAttribute('href',newEntryUrl);
})

The problem is because you are using a relative URL as the href, causing the browser to append this to the current URL you are looking at.
In your example, your button will be set as follows:
<a class="btn btn-success" id="newEntrybtn" role="button" href="127.0.0.1/...">
And clicking on it will append the href to the current URL since the browser will consider it as a resource of the current page.
Following your example, using an absolute URL will allow you to go directly to the URL as you have it set as long as you know the full structure (in your case, you are missing the protocol/scheme):
<a class="btn btn-success" id="newEntrybtn" role="button" href="http://127.0.0.1/...">
Or ideally you should use a relative URL by defining correctly the segment of the URL it represents (defining the path from your host where the resource is located):
<a class="btn btn-success" id="newEntrybtn" role="button" href="/wiki/_create/...">
(notice how the URL starts with a slash and omits the server host and protocol).
It is preferred in most cases to use relative URLs to make your code run regardless of the server (environment), meaning it will always use the same server or protocol of the current URL. But it's up to you based on your needs.
References:
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL#absolute_urls_vs_relative_urls

I found a good solution without using JavaScript, in just one line of code:
<a class="btn btn-success" href="/wiki/_create/?slug={{ search_query }}" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a>
Thanks to those who have posted an answer, you have inspired me a lot.

Related

How to add a new webpage to ASP.NET MVC

Right now I am making a MVC that has a default page that loads up. From this page, the user can press a button to go to the next page. So far, I have made the first page work and a button that goes to a specified URL for the second page. The only issue I am having is making the view that I want to correspond to the second page have the correct URL.
Here is the code for my button link to the next URL
<input type="button" value="Create" onclick="location.href='#Url.Action("IndexA", "HomeController")'" />
I guess my question is how do I make my view have the specified URL that I want so it can be accessed?
I used something like this in my own project.
#if (Request.UrlReferrer != null && Request.UrlReferrer.Host == Request.Url.Host)
{
<a href="#Request.UrlReferrer" class="dbtn btn-11">
<i class="fa fa-undo"></i>
#Resources._Action_Back
</a>
}
only came from within the domain that was published I said let the button appear.
there is something like add controller in default settings controller name + controller. So just write the name there.
I had to put "home" in the URL.Action instead of "HomeController"
Please see this photo.
https://ibb.co/4SS5nYh
You add a new controller and a new view for that new page (also a model). I have called mine Test.
Then in the button. you call them with url action.
<input type="button" value="Create" onclick="location.href='#Url.Action("Index", "Test")'" />

"Could not parse reminder error" - django

When jsevent triggered , it forwards link parameter to data-url attribute of a button and when user click that button it redirects to django backend view but there is a problem with parsing line of JS
$('#btn_del').attr('data-url',{% url 'event_delete' + event.id + %});
is there any chance to combine that syntax ?
Thank you , have a nice days.
JS:
eventClick: function(event, jsEvent, view) {
$('#modalTitle').html(event.id);
$('#btn_del').attr('data-url',`{% url 'event_delete' ` + event.id + `%}`);
$('#calendarEditModal').modal();
console.log(event.id);
}
url.py
....
url(r'^event/(?P<pk>\d+)/delete/$', event_delete, name='event_delete'),
....
Html button that redirects to django
<button id="btn_del" type="button" class="btn btn-primary js-delete-events" data-url="">
<span class="glyphicon glyphicon-pencil"></span>
Edit
</button>
Result should be like this format event.pk is going to be our parameter numeric value , it's ok.
<button type="button" class="btn btn-primary js-delete-events" data-url="{% url 'event_delete' event.pk %}">
<span class="glyphicon glyphicon-plus"></span>
button
</button>
/event/1/update/ is the last result of seen from browser inspect. But I need to write inside jsEvent with django syntax to able to reach backend view which is {% url 'event_delete' event.pk %} something like that.
No, it cannot be done that way... Parsing of your templates (the {% url %} tag) is done on the server before even the browser receives anything. Browser doesn't know what template tags are you using.
On the other side, JavaScript is executed in the browser, so template language has also no knowledge about variables inside it.
Solution for that is to use a package like Django JS Reverse. The second one is to pass full URL to the JavaScript, just like it receives the ID of the item.

Pass django variable to javascript file without security issues

Clarification:
I really don't want to embed my js in my html. The suggestions I'm
getting, like, this or that post might contain the possible answer,
well in those answers, they embedded their js in html. Both my
js and html is large. So embedding will surely make them messy and
hard to debug
In my project there's a module where user can see details about product and add products to cart. For this he needs to specify the number of products he wants to add. It looks like
For this I have a + and - icon. I have a js file where it increments or decrements each time + or - has been clicked.
Now, what I want is this:
A user can add products but if the total number exceeds the number of
products stored in the database, he can't add products even if he
click the + button. For example, if there are 4 items and he clicked
5 times then on the 5th click the amount will remain 4, won't
increase.
So I need a django variable in my js file. I looked up how to do that, and I found some solutions.
Some solution says var data = '{{data|escapejs}}' this while some solution says
<script>
var myTable = {% autoescape off %}{{ table_data }}{% endautoescape %};
</script>
But I don't want to embed js on my html like this. Here is my js file:
function incrementValue()
{
var value = parseInt(document.getElementById('quantity').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('quantity').value = value;
}
And my html, from where I am calling this js like this:
<span class="btn btn-default btn-lg btn-qty" onclick="incrementValue()">
<span class="glyphicon glyphicon-plus" aria-hidden="true">
</span>
</span>
<input class="btn btn-default btn-lg btn-qty" id="quantity" value="0" />
<span class="btn btn-default btn-lg btn-qty" onclick="decrementValue()">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</span>
</span>
What is the best way to pass django variable to js or, How should I pass the django variable to my js so that there will be no vulnerability or no security issues and also I don't want to embed js in my html.

Initiating AJAX request from multiple buttons on the same page in Django

Ok, so I'm trying to add voting to my website(django based) using Ajax. I have multiple entries in one page, But right now my code only let users vote on the first entry. Please help me with the code so that users can vote on all of them.
First is the html code, basically it's just a vote button for users to vote
{% for answer in answers %}<!-- django template -->
<strong id="vote_count">{{ answer.votes }}</strong> people vote this answer
{% if user.is_authenticated %}
<button id="vote" data-answerid="{{answer.id}}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Vote
</button>
{% endif %}
{% endfor %}<!-- end django template -->
Second, below is the django view that process the request
#login_required
def vote_answer(request):
answer_id = None
if request.method == 'GET':
answer_id = request.GET['answer_id']
votes = 0
if answer_id:
answer = Answer.objects.get(id=answer_id)
if answer:
votes = answer.votes + 1
answer.votes = votes
answer.save()
return HttpResponse(votes)
below is the url mapping:
url(r'^like_category/$', views.like_category, name='like_category'),
Finally is the javascript
$('#vote').click(function(){
var answerid;
answerid = $(this).attr("data-answerid");
$.get('/vote_answer/', {answer_id: answerid}, function(data){
$('#vote_count').html(data);
$('#vote').hide();
});
});
Again, my problem is that of all the entries I have in one page, with this code I can only vote the first one. How can modify it so I can vote all of them
You need to use class instead of id on <button>, so that multiple buttons can share the same jQuery event handler.
<button class="vote" data-answerid="...">
Then you can do the following in JavaScript:
$(document).on("click", ".vote", function(){
var answerid;
answerid = $(this).attr("data-answerid");
$.get('/vote_answer/', {answer_id: answerid}, function(data){
$('#vote_count').html(data);
$('#vote').hide();
});
});
This will bind the event handler to click any <button class=vote>.
Also you should do AJAX POST instead of GET by HTTP semantics, because voting is a state changing operation. Otherwise the browser or the web proxies may cache the result (though jQuery have its own cache buster).

using django tags with javascript function during hyperlinking

I have a html code snippet
home
I want to add a call to javascript funciton in the end of url,
if home url is http://localhost/home then above code generates
http://localhost/home?p=1
however I do not understand how to add a parameter at the end of it.
following does not work
<a href = "{% url home %}?p=1"+getParameters()>home</a>
You're not using template tags properly (see: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#url)
Correct:
{% url <url-name> %}
Now "{{ url home }}" returns empty string so you're adding GET param for current URL.
{{ x }} form returns variable named "x".
Adding parameters to URL using JS
This is simple example of on click script changing anchor url:
anchor
<script>
function getParameters(elem) {
elem.href = elem.href + "&abc=1";
}
</script>

Categories