How to set download url in a table row - javascript

I've this javascript function that takes the ajax call's result and build a html table with it. This table rapresents list of reports.
Each row of a table is composed by report's filename and date of creation, and when I click over it a new browser page is opened showing me the document. But I want to download it. How can I get it?
Code:
function report_call(){
$.ajax({
type: 'GET',
url: "/rest/v2/reports/",
dataType: 'json',
success: function (data) {
$("#modal-body").html('')
const YOURREPORTS_ROW = "yourReportRow";
const YOURREPORTS_TABLE = "yourReports-table-content";
let table = $(`#${YOURREPORTS_TABLE}`);
table.html('')
for(const key in data) {
if(data[key].length == 0){
continue
}
data[key].forEach(report_type => {
let url = report_type[2] // take file url
let fname = report_type[0];
let fname_td = $(`<td>${fname}</td>`);
let date = report_type[1];
let date_td = $(`<td>${date}</td>`);
let onclick = "";
if(url !== ""){
onclick = `onclick="window.open('${url}', '_blank');"`;
}
let row = $(`<tr class="${YOURREPORTS_ROW}" [data-file="${fname}"] data-date="${date}" ${onclick}>`);
row.append(fname_td);
row.append(date_td);
table.append(row);
})
}
}
})
}
On the web I read that I can use "download" keyword in tag , but here the situation is different. I try in this way, it does not work.
Sorry for the ignorance.

Use an anchor tag with download attribute like below. You can also add another td for the download link. Remove the onClick event in row.
let date_td = $(`<td>${date} <a href=${url} download>Download</a></td>`);

Related

Replace table instead of append jquery

I have the following code segment that grabs user input from an HTML form, and then reads a CSV file, and grabs corresponding data to display to my website. If I submit another 'searchTerm' after the initial one in my form, it appends the new row of data from the csv file to the page, and I want it to replace instead. When I try to replace the row however, all my data vanishes.
function submitForm(){
nameValue = document.getElementById("searchTerm").value;
//document.getElementById("display-results").innerHTML = nameValue;
location.href = "#page-3";
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
if (cellData == nameValue) {
row.append($('<td>'+rowData[1]+'</td>'));
}
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "mainFile.csv",
success: function (data) {
parsed = Papa.parse(data).data;
$('#display-results').append(arrayToTable(Papa.parse(data).data));
}
});
}
As you can see in the image, it appends the content rather than replacing the first array.
Remember to just replace the table, not the entire display-results element (except the first time you build the table).
if($('#display-results table').length === 0) // append if you haven't built the table yet
$('#display-results').append(arrayToTable(Papa.parse(data).data));
else
$('#display-results table').replaceWith(arrayToTable(Papa.parse(data).data));

How to find the id of the html while looping through <tr> in javascript/jquery

I'm working on a queue management page where we have multiple Html tables on a single page and each table holds 10 values including name and image, now I wanna remove a row from the table when the present button is pressed and I did it using this following code
function removePresent() {
const urlParams = new URLSearchParams(window.location.search);
const HallNo = urlParams.get('hallno');
const TvIP = urlParams.get('tvip');
$.ajax({
url: '#Url.Action("PresentDisplayRemover")',
type: "GET",
data: { 'HallNo': HallNo, 'TvIP': TvIP },
contentType: "application/json",
success: function (response) {
$.each(response, function (j, e) {
const rows = Array.from(document.getElementsByTagName('TD'));
$.each(rows, function (i) {
if ($(rows[i]).text() === e.StudentId) {
$(rows[i]).parent().remove();
}
});
}
});
}
Now my flow also requires me to find the Id of the matched to increment a counter, I have no idea how to do it and I also tried searching online but I ended up finding nothing,I'm relatively new to js and jquery since my main workflow only consists of me working with .NET so any help would be great, Thank You.

Ajax sends two files at one time through one onclick event in JavaScript

jQuery AJAX seems to be sending two requests at once when I use the onclick event with JavaScript in a tag. I click once, and that seems ok, but when I change the id value to an invalid id value, it sends two requests to the PHP file. I think the problem may be caused by the browser caching JavaScript code.
Here's is the JavaScript code I'm using to generate the query:
function unlike_image(id, image_id, obj) {
var url_unlike_image = base_url + 'profile/unlike_image';
$.ajax({
type: "POST",
data:
{
user_id: id,
image_id: image_id
},
url: url_unlike_image,
success: function(data) {
if (data.status=='error_exists') {
alert('This image not exists');
}
if (data.status=='success') {
//like = like - 1 for view
var str = $(obj).next().text();
var n = str.length;
str_like = str.substring(1, n-1);
var number_likes = parseInt(str_like) - 1;
$(obj).next().text('('+number_likes+')');
//change event click unlike
$(obj).text('Like');
$(obj).attr('onclick', 'like_image('+id+' ,'+image_id+ ',this); return false');
}
}
});
}
After changing the true id to the wrong id, I check the website traffic, I see two instances where unlike_image is called. The first is with the true id, and the second is with the wrong id.

How can I capture the attribute id from a dynamically generated html?

I am pretty sure this is not so complicated but I have been for hours trying to figure out how to catch the id of this dynamically generated anchor tags.
What I do in my code is that everytime a text input changes, theres an ajax request that goes to a php file and returns me a json array with the prices then I render this results of search in buttons that will be clickable to do other types of request but so far here's where I'm stuck.
heres's the code that loops through the array and renders this buttons (NOTE:The Id of the buttons are variables rendered by the function too.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
success: function(data){
$('#loader_s').hide();
var jsarray = JSON.parse(data);
var length = jsarray.length;
for(i=0;i<jsarray.length;i++){
var index1 = i;
var index2 = Number(i++) + 1;
var index3 = Number(i++) + 2;
$('#modal-bod').append('<a onclick="renderProds();" class="btn btn-default-item prod_sel" style="margin-top:10px;" id="'+index3+'" data-dismiss="modal">'+jsarray[index1]+' <span class="pull-right" st>lps. '+jsarray[index2]+'</span></a>');
}
}
Then here's the function renderProds()
function renderProds(){
var id = $(this).attr('id');
alert(id);
}
the alert is just to try and catch the values for testing purposes, but what really goes there is another Ajax request.
The only thing I get here is that the var Id is undefined...
You can pass object like
function renderProds(obj) {
var id = obj.id;
alert(id);
}
Pass invoker object like
onclick="renderProds(this);"
I would do :
onclick="renderProds(this);"
function renderProds(that){
var id = that.id;
alert(id);
}
You use jQuery.. so USE jQuery !
Ajax can do the JSON.parse for you with just dataType: "json".
The inline onclick is bad practice.
Move the success function to make your code more readable.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
dataType : 'json',
success: productsUpdate
});
function renderProds(event){
var id = $(event.target).attr("id");
alert("Id is:"+id);
}
function productUpdate(data){
$('#loader_s').hide();
for(i=0;i<data.length;i++){
var link = $('<a>....</a>');
link.click(renderProds);
$('#modal-bod').append(link);
}
}
Now, this is readable.
Complete the link creation with your code, without the onclick, remove the inline css and use a real css selector and finally, check this ugly Number(i++)+ .... it looks so bad.

XML find each javascript request , another each in the main each

i've been working on android application with the help of phonegap framework .I've made 1 php -xml file to parse the data from my site to application. The problem i have is that when i click button , i want to get all the <vic></vic> separated of the clicked cat_id
Heres the link with xml file
http://smeshnoto.eu/rss/mobile_vicove_cats.php
At the moment i have this code:
function showVicoveKategorii(){
var xml = '';
$.ajax({
url: "http://smeshnoto.eu/rss/mobile_vicove_cats.php",
dataType: 'xml',
success: kategorii,
error: function () {
alert('Грешка в сървъра');
}
});
}
function kategorii(xml){
var obj = document.getElementById("vicove_kategorii_id");
$(xml).find('category').each(function(){
var catname = $(this).find('cat_name').text();
var catid = $(this).find('cat_id').text();
var titlevic = $(this).find('title_vic').text();
var descvic = $(this).find('desc_vic').text();
addContent(obj, ''+catname+'');
});
}
I want when i click the button the alert to be all <vic></vic> with <br> for example after every element , of course those <vic></vic> to be from the clicked category (cat_id)
The solution is to use http://smeshnoto.eu/rss/mobile_vicove_cats.php?cat_id=ChosenID
so you can get the items from the chosen id :)

Categories