Html href attribute on the condition - javascript

I am new to web-development. I am using angular-js .Here , I have a functionality like , when I click on a button then I get a response from back-end , If that is true then I am changing that button to download button. So, after clicking on this, I am doing an ajax call , with it I get a url, with which I can download a respective file. So, Here I am using a href to download the file.So, My concern is when I click on download that time only it should get that url and also by using href should download a file.
My code is like -
HTML -
<button class="btn btn-labeled btn-info" title= "{{ isAvaliable ? 'Download' : 'click to track'}}" ng-disabled="!file.processed" data-ng-click="performAction(file.attributes.name,file.attributes.cn, isAvaliable)">
<a ng-href="{{url}}" target="_blank" ></a>
<i ng-class="isAvaliable ? 'fa fa-download' : 'glyphicon glyphicon-text-width'" aria-hidden="true"></i>
</button>
controller
$scope.performAction = function(fileName, cn, isAvaliable) {
if(isAvaliable) {
$scope.downloadfile(fileName);
} else {
$scope.moveTofolder(fileName,cn);
}
};
$scope.downloadfile = function(fileName) {
uploadService.downloadtracker(fileName)
.then(function (response) {
$scope.url = response.data;
},
function (error) {
})
.finally(function () {
}
);
};
$scope.moveTofolder = function(fileName,cn) {
// Here also I am calling some service and I am getting response .\
/// Here I am changing the button
$scope.isAvaliable = true;
}
So, Here I am getting some problems, because of the href and the downloadButton . So, How can I call a function on download click and get the URl and at the same time get that url and use it in the href so that It can download the file as well. Href and downloadButton are for the same purpose.Thanks in advance.

Try like below. Don't mingle <a> and <button> because you have button click and also anchor click event.
<a ng-href="{{url}}" ng-click="Download()" ></a>
$scope.Download = function(){
//some other code
window.open($scope.url);
}
<button class="btn btn-labeled btn-info" title= "{{ isAvaliable ? 'Download' : 'click to track'}}" ng-disabled="!file.processed" data-ng-click="performAction(file.attributes.name,file.attributes.cn, isAvaliable);downloadfile
(url)">
<i ng-class="isAvaliable ? 'fa fa-download' : 'glyphicon glyphicon-text-width'" aria-hidden="true"></i>
</button>

You just need to add download attribute in your button
<button class="btn btn-labeled btn-info" title= "{{ isAvaliable ? 'Download' : 'click to track'}}" ng-disabled="!file.processed" data-ng-click="performAction(file.attributes.name,file.attributes.cn, isAvaliable)" ng-click=“downloadfile
({{url}})”>
<!— <a ng-href="{{url}}" target="_blank" ></a> —>
<i ng-class="isAvaliable ? 'fa fa-download' : 'glyphicon glyphicon-text-width'" aria-hidden="true"></i>
</button>
Add $http in controller
$scope.downloadfile = function(fileName) {
//here I am calling a service and I am getting a responce which contains a url.
$scope.$emit('download-start');
$http.get(fileName).then(function(response) {
$scope.$emit('downloaded', response.data);
});
$scope.url = responce.data;
}
Hope this help you

Related

ajax not work when click open in new window after right click in django template

i created a link with ajax this is a html coded:
<a id="post_click" href="{{ post.online_url}}" rel="nofollow">
<button class="w-100 " type="button" name="button">
<span class="">link</span>
</button>
</a>
and this is ajax :
$(function () {
$('#post_click').on('click', function () {
var Status = $(this).val();
var id = {{post.id}}
$.ajax({
url: "/post-click/" + id,
data: {
},
dataType : 'json'
});
});
});
if i push left click ajax work fine in sever side, but when i push left right click and choose open in new window ajax doesnt work
you have to set the good url in href for doing that :
<a id="post_click" href="/post-click/{{post.id}}" rel="nofollow">
link
</a>

How to append big HTML snippets into DOM with Javascript?

I have an app which uses EJS templating to populate data.
In order to add new projects I have made a simple input form which takes all required parameters.
After an input completed an Ajax request being sent, on success I want to inject this snippet into DOM.
In simple words - After new project added I want to display play instantly by injecting into DOM without reloading the page
Is there an elegant way of inserting this div ladder as a template into DOM? It works,
<div class="projects">
<div class="projectHeader">
<div class="projectTitle">
<span>
<a data-toggle="modal" data-target="#editDeadLineModal">
<i data-id="<%=project.id%>" class="projectDeadline far fa-calendar-alt fa-2x" data-toggle="tooltip" data-placement="top" title="Set Deadline"></i>
</a>
</span>
<h5 class="projectName <%=project.id%>" data-toggle="tooltip" data-placement="top" title="Deadline <%=deadline%>" style="align-items: center;">
<%=project.name%>
</h5>
<%}%>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i id="editProjectName" class="editProject fas fa-pencil-alt" data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
<i class="separatorDash fas fa-minus"></i>
<span data-toggle="tooltip" data-placement="top" title="Delete Project">
<a data-toggle="modal" data-target="#deleteProjectModal">
<i id="deleteProject>" class="deleteProject far fa-trash-alt" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
</div>
What I have tried is recreating the entire div ladder in string and append it to parent node.
Like this:
// Add new Project
$('#addNewProjectBtn').on("click", function() {
$("#newProjectModal").on('show.bs.modal', function() {
$(".confirmNewList").on("click", function(event) {
var url = '/addNewList';
var newListTitle = $("#newListNameInput").val()
event.preventDefault();
$.post({
url: url,
data: {
listName: newListTitle
},
success: function(result) {
$("#newProjectModal").modal('hide')
$("#newListNameInput").val('');
var id = result.data.id
var name = result.data.name
//Append new project
$(".projects").append("<div class='project col-4' id='project" + id + "'> <div class='projectHeader'> <div class='projectTitle'> ...and so on until the end")
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
})
In simple words - After new project added I want to display play instantly by injecting into DOM without reloading the page
Is there an more elegant and specially efficient way of inserting this div ladder as a template into DOM?
The method which I have tried above - works, But on attempt to interact with it by calling modals - modals do not get it's data-*, as well the bootstrap tooltips don't work.
you can try create new html file instead, and append like this in your page
$.get("yourfile.html", function (data) {
$("#appendToThis").append(data); // or use .html();
});
OR you can directly pass this HTML structure from your backend, so you can directly use append function.
After some research I discovered that the event handler can be delegated.
Since the html snippet I am trying to append to projects is added after document.ready (document is loaded and handlers are bind) the only thing required to make the new snippet be active on event is to delegate the event handler to the parent of element that is appended.
Like this :
$("body").delegate("#addNewProjectBtn", "click", function() {
$("#newProjectModal").on('show.bs.modal', function() {
$(".confirmNewList").on("click", function(event) {
var url = '/addNewList';
var newListTitle = $("#newListNameInput").val()
event.preventDefault();
$.post({
url: url,
data: {
listName: newListTitle
},
success: function(result) {
$("#newProjectModal").modal('hide')
$("#newListNameInput").val('');
var id = result.data.id
var name = result.data.name
//Append new project
$(".projects").append("<div class='project col-4' id='project" + id + "'> <div class='projectHeader'> <div class='projectTitle'> ...and so on until the end")
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
})
By delegating the event handler to it's parent - the event handler is preserved in the parent.

javascript change class of that button and other elements

I'm trying to buil a like/dislike system for a project and I'm having some trouble in the last part.
The like/dislike system is working, but I would like to have the button change automatically after the click (change class and icon).
This is working based on many rows and each of them is in this way (Like):
<button type='button' onClick='LikeDislike($row_data[id], $row_data[cat],
$row_data[scat], $row_data[sscat], $_SESSION[user_id]);' class='btn btn-info
pull-right btn-xs'><i class='fa fa-thumbs-up'></i></button>
In PHP I already made the code so the button shown at page load is to Like or Dislike based if there is a like or not.
The button to "Dislike" is the same, only changes the class of the button and the class of the :
<button type='button' onClick='LikeDislike($row_data[id], $row_data[cat],
$row_data[scat], $row_data[sscat], $_SESSION[user_id]);' class='btn btn-
danger pull-right btn-xs'><i class='fa fa-thumbs-down'></i></button>
I have this code working to set the like/dislike, but I can't get a way to change the class of the button and the class that's inside that specific button:
$.ajax({
type:'POST',
url:'inc/like.php',
data:'id='+id+'&cat='+cat+'&scat='+scat+'&sscat='+sscat+'&uid='+uid,
success:function(msg){
if(msg == 'err'){
/** alert('Some problem occured, please try again.'); **/
$.toast({
heading: 'Error!',
text: 'There was a problem processing your like.',
position: 'top-right',
loaderBg: '#ff6849',
icon: 'error',
hideAfter: 3500
});
}else{
$.toast({
heading: 'Success!',
text: msg,
position: 'top-right',
loaderBg: '#ff6849',
icon: 'success',
hideAfter: 3500,
});
if(msg == "Like added."){
alert(1);
//** Remove Class btn-info and add class of button to btn-danger.
//* Change class of the <i> element to fa-thumbs-down (inside that button)
}else{
alert(2);
//** Remove Class btn-danger and add class of button to btn-info.
//* Change class of the <i> element to fa-thumbs-up (inside that button)
}
}
}
});
}
So, as I did it in PHP, after some likes/dislikes, some icons in the list are diferente (some are to like and other to dislike)
Please note that should be only effective for that button in specific and not in all buttons of that page.
I can't get an easy way to do it. Anyone could help me?
Thanks.
You can pass your button to your function LikeDislike by using this keyword.
<button type='button'
onClick='LikeDislike(this, $row_data[id], $row_data[cat], $row_data[scat], $row_data[sscat], $_SESSION[user_id]);'
class='btn btn-info pull-right btn-xs'>
<i class='fa fa-thumbs-up'></i>
</button>
after that, where you handle your ajax code, you can do the following :
function(ele, a, b, c, d) {
$.ajax([...],
success: function(){
// Do whatever you like...
ele.find('> i').removeClass('some-class').addClass('other-class');
}
);
}
I did it, hope that would be the best way to do it.
For those that need this information, I left here the answer:
First I set the button an ID and the class another one.
The button ID is set as 1,2,3,4...
The elemento inside the button is set as 1_1, 2_1, 3_1..
Then, in the if statement (commented above):
if(msg == "Like added."){
document.getElementById(id).className = 'btn btn-danger pull-right btn-xs';
document.getElementById(id+"_1").className = 'fa fa-thumbs-down';
}else{
document.getElementById(id).className = 'btn btn-info pull-right btn-xs';
document.getElementById(id+"_1").className = 'fa fa-thumbs-up';
}

Add Friend with Ajax - Django

I'm using Django-Friends
I'm trying to have it so when a user clicks on the add friend, the button disappears(or ideally says Request sent). However, when I click the button, it doesn't disappears. I am new at Django and Ajax, so I'm assuming that this is an error on my part. Most likely the HttpResponse.
That part actually confuses me a lot. The HttpResponse, render, render_to_response, etc. I know that I can use render or render_to_response when I want to load a template. But what if I don't want to load up a new template or go to a new page? Like I want to be able to complete an action like add a friend, or add a page, etc; all on one page. I know you can use ajax to do it, but I don't know the django technical aspect of it.
Anyway, here's my code. Right now, nothing happens. The button doesn't disappear, and there is no friendships request sent.
profile.html
<div class="text-center">
<div>
"{{currUserprofile.tagline}}"
</div>
{{currUser.profile.city}}, {{currUser.profile.state}}
{{currUser.id}}
</div>
<!-- <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
--> <!--Find a way to signify looking or not looking to mentor -->
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
ajax.js
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
})
views.py
#login_required
def profile(request, id):
context = RequestContext(request)
currUser = User.objects.get(pk = id)
profile = UserProfile.objects.filter(user = currUser)
return render_to_response('myapp/profile.html', {'currUser': currUser, 'UserProfile': UserProfile}, context)
#login_required
def addfriend(request, id):
context = RequestContext(request)
other_user = User.objects.get(pk=id)
new_relationship = Friend.objects.add_friend(request.user, other_user)
profile = UserProfile.objects.filter(user = other_user)
return HttpResponse(new_relationship)
Here is a working JSFiddle, but you can't post data {profile_id: profile_id}with a getyou should use a postor add the data as params, as I did:
HTML:
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
JS:
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/?profile_id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
});

twitter bootstrap modal -- how to pass data to callback function

is there a way to pass additional data to bootstrap modal function callback?
for example, lets say my link that causes the modal to open has an extra attribute in it with a bit of useful data in it, how could I reference that attr?
HTML
<span listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
JS
$('#editTaskList').on('show', function () {
// get the source of the click, and then get the data i need.
});
Could this work for you ?
<span listid="80" href="#editTaskList" data-toggle="datamodal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
var $editTaskList = $('#editTaskList');
$('body').on('click.modal.data-api', '[data-toggle="datamodal"]', function (e) {
var $this = $(this);
$editTaskList.data('anyAttr',$this.data('anyAttr'));
$editTaskList.modal('show');
e.preventDefault();
})
$editTaskList.on('show', function () {
var myData = $editTaskList.data('anyAttr');
});
I know that this is an old question, but this is the first thing i've found on google. So, I want to put some important information here...
You NEED to put your callback function binded on events BEFORE you call the modal, for example:
$('#modal').on('shown', function(){
// Do something when the modal is loaded
});
$("#modal").modal();
This is very important and helped me a lot, so, here it is...
Like this -
<span id="modal_opener" data-extrastuff="stuff" listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
$('#modal_opener').click(function() {
var stuff_i_want = $(this).attr('data-extrastuff');
});

Categories

Resources