I am creating a web page for a project using Ruby on Rails that will run scripts selected by a user and will build elements on the bottom of the page using JavaScript to display the results. Each result element consists of a Bootstrap collapsible presentation area containing the results. I am implementing a download link at the bottom of each presentation block, which just saves all the text inside as a .txt file to be downloaded. I am using JavaScript blob's to achieve this, but have run into an issue. I need to have a limitless number of links to hold data to be downloaded, but every time a new link is made the previous one stops working for downloads. I have tried saving the blob links into an array and returning resulting link from that, to no avail. The function that builds the blobs is as follows:
var textFile = null,
makeTextFile = function(text){
data = new Blob([text], {type: 'text/plain'});
if(textFile !== null) { window.URL.revokeObjectURL(textFile); }
textFile = window.URL.createObjectURL(data);
return textFile;
};
I could handle the downloads using Ruby on Rails "send_file", but that requires the web page to reload which will lose all the other results. The code that builds the result elements is as follows:
if(document.getElementById("dig").checked == true)
{
$('#dig_wait_img').addClass('hidden');
$('#dig_loading_img').removeClass('hidden');
results = $.ajax({
type:"POST",
url: "/console/discovery/dig",
data: { domain_name : domainInput },
success: function(data) {
resultArr.push(data["value"]);
$('#dig_loading_img').addClass('hidden');
$('#dig_check_img').removeClass('hidden');
$("#results")
.append(
$("<div class=\"panel panel-default\">")
.append(
$("<h4 class=\"panel-title\">")
.append(
$("<a data-toggle=\"collapse\" href=\"#collapse" + count + "\">DIG - " + domainInput + "</a>")
)
)
.append(
$("</h4>")
)
.append(
$("</div>")
)
.append(
$("<div id=\"collapse" + count + "\" class=\"panel-collapse collapse\">")
.append(
$("<pre><div class=\"panel-body\" id=\"body" + count + "\">" + data["value"] + "</div><a id=\"" + count + "\" href=\"" + makeTextFile(data["value"]) + "\" download=\"" + data["file"] + "\">Download</a><div class=\"panel-footer\"></div></pre>")
)
)
.append(
$("</div>")
)
.append(
$("</div>")
)
);
count++;
},
error: function(data)
{
$('#dig_loading_img').addClass('hidden');
$('#dig_x_img').removeClass('hidden');
},
});
}
If anyone has any experience with handling multiple download links made with blob on a static web page, or if you just have any suggestions in general, any help would be appreciated. Thanks in advance
Oh the joys of being tired... After taking a step back and thinking maybe it's not how I'm approaching the problem, but something I assumed was required. The actual problem didn't reside in how I was trying to store the blob links, but the fact that the textFile variable doesn't get reset to null, and I check if the file is not null and revoke the link if so. Removing the if statement in the makeTextFile function solved the problem!
Related
I'm generating a url action by replacing my RoutingValueDictionary querystring parameter by the value sent to a javascript function
When building a grid, its columns are generated using template.
For each column generated, I return a url:
columns.Bound(c => c.ItemId).Title("Item #").Width("150px").Locked(true).Lockable(false).ClientTemplate("#=showDetails(data.ItemId)#");
Then, I'm using a function where I build the url using #Url.Action():
function showDetails(data) {
var ItemDetailsUrl = "#Url.Action("Index", "ItemDetail", new
System.Web.Routing.RouteValueDictionary(new { id = "data" }), null, Request.Url.Host)".replace("data", data);
var returnText = "<a target='_blank' href='" + itemDetailsUrl + "'>" + data + "</a>";
return returnText;
}
The way I did that, works fine. But I'm not sure if that is an efficient though.
Is there any other ways to do it?
So I'm trying to make a mini app where I can access a bunch of drawing references I pinned on my pinterest board. I managed to get ajax call to work and SOME of the images are appending but then some do not.
I originally used the url property but then everything broke so I switched to link where I managed to get some images but some were still broken. Afterward I added an if statement to weed out images that didn't have a link url.
This worked as I can see the urls popping up in the console, they just don't render images.
Does anyone have any ideas?
//on document start up
$(document).ready(function(){
//declare the global variables:
var queryURL, results, resultURL, imageHolder, image;
//create the url where we will get the images from pintrest
queryURL = "https://api.pinterest.com/v1/boards/gasulliv/concept-art-inspiration/pins/?access_token=AXHj1v5z8_oy5kcy6NtLlZaoY_XAFQ-h5sli9PNErKPqdSA7cQAAAAA&fields=id%2Clink%2Cnote%2Curl";
//empty the div
$("#images").empty();
//performing ajax call
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
console.log(response.data);
//creating a variable for the repsonse data
results = response.data;
//loop through the data
//this is the shorthand for a forloop
for (var i in results){
resultURL = results[i].link;
console.log(results[i].url);
if (results[i].link !== ""){
//put results in a variable and then with each loop append them to the div
imageHolder = $("<div class='imageHolder'>");
image = $("<img>").attr("src", resultURL);
imageHolder.append(image);
$('#images').prepend(imageHolder);
}
}
});
});
Figured it out.
Just a head's up if you do ever run into this problem with pinterest's api, you'll need to make sure your queryURL includes the original be sure to return it like this:
resultURL = results[i].image.original.url;
this should return the original image's url
Don't make your access token accessible to everyone !
then for readability, you can make a code like this :
var tpl = [
"<div class='results'>",
"<div class='card'>",
"<div class='card-result'>",
"<p class='pBlack20'>" + data.response.docs[i].lead_paragraph + "</p>",
"<p class='pBlack14'>" + data.response.docs[i].pub_date + "</p>",
"<a class='FontRed link' target='_blank' href='" + data.response.docs[i].web_url + "'>For more detail</a>",
"<hr>",
"</div>",
"</div>",
"</div>"
]
$('.results-content').append(tpl.join(''));
I'm brand new to webdev, I'm trying to build a web app that gets a new quote whenever the button #getQuote is clicked.
This is my my js code:
$(document).ready(function() {
// function get_new will get a new JSON object
function get_new() {
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content.slice(3, -6);
var author = '- ' + a[0].title;
var my_quote = $('<i class="fa fa-quote-left"></i> ' + quote + ' <i class="fa fa-quote-right"></i>');
$('.quoteBody').html(my_quote);
$('.quoteAuthor').html(author);
// tweet the quote
$("#tweet").click(function() {
$(this).attr('href', 'https://twitter.com/intent/tweet?text=' + '"' + quote + '" - ' + author).attr("target", "_blank");
});
});
}
// calling function to appear as default
get_new();
// when clicked, get new quote
$('#getQuote').click(function() {
get_new();
});
});
Any help would be appreciated guys.
Here's the codepen for anyone interested:
https://codepen.io/tadm123/pen/YNvdyr
As others have pointed, it's just a cache issue on codepen.
Add this line to your code to set cache false:
$.ajaxSetup({ cache: false });
Be careful using this in a live environment, you dont want to affect all your ajax requests with cache:false. So I'd recommend you using a normal jQuery ajax call and set the property cache to false specifically to this function only:
$.ajax({
cache: false,
url: "/path/to/file.json",
dataType: "json",
success: function(data) {
...
}
});
Your code is 100% right. It just so happens that the browser is caching the result of the url you're accessing. I noticed that Codepen was caching the result and my browser was caching it too when I tested it with files on my computer. So after it hits that URL the first time, it thinks something along the lines of "Oh, I've already gone to this URL and I already know what the result is. So to save time, I'll just give it the same data as before."
To combat this (this might be considered hacky?), add the current time to the end of the URL (because the time will always be different) like so:
function get_new(){
var currentDate = new Date().getTime(); // create new date
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&date=" + currentDate, function(a) { // add it to end of URL
var quote = a[0].content.slice(3,-6);
var author = '- ' + a[0].title;
var my_quote = $('<i class="fa fa-quote-left"></i> ' + quote + ' <i class="fa fa-quote-right"></i>');
$('.quoteBody').html(my_quote);
$('.quoteAuthor').html(author);
// tweet the quote
$("#tweet").click(function(){
$(this).attr('href', 'https://twitter.com/intent/tweet?text='+ '"'+ quote + '" - ' + author).attr("target","_blank");
});
});
}
Also sometimes the result will come slowly, but I think that's because of the speed of the server your requesting the quotes from. Another challenge can be to have a loader show while it's getting a quote from the server.
Put cache false in your URL. This is because you are getting same data again and again
https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&cache=false&callback
Close... to get it to work with the console closed, the $.ajaxSetup({ cache: false }); didn't work. However, randomizing the URL did:
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=&cache="+Math.random(), function(a) {
Recently I've been working on a custom twitch chat widget for my stream and I've come across a few issues I need to address first.
Here is the code:
var userName = obj.user;
$.ajax({
type: "GET",
url: "https://api.twitch.tv/kraken/channels/" + userName,
headers: {
'Client-ID': 'ql93k2lg41xsnebz7kgyfjsrg28j532'
},
success: function(data1) {
var userLogo = data1.logo;
if (userLogo === null) {
userLogo = "https://static-cdn.jtvnw.net/jtv_user_pictures/xarth/404_user_70x70.png";
$("#logo").prepend("<div id='logo' class='image'>" + "<img src='" + userLogo + "' style='width:40px;height:40px;'>" + "</div>");
} else {
$("#logo").prepend("<div id='logo' class='image'>" + "<img src='" + userLogo + "' style='width:40px;height:40px;'>" + "</div>");
}
}});
As you can see the script grabs the username from obj.user to create the api url link for each user. Then we pull the logo from the users api.
If logo returns null then we set it to the default image link. Otherwise we pull the url from the user api for their logo and display it on screen.
Now I want to take these urls and have them save to my projects directory as .png's as they are loaded for the first time. This way if we have the image already on hand we can call it from our own personal database instead of constantly calling for it from the twitch api.
How could I edit my script to add a function to check if the .png is in directory, then if not pull it from the api call and save a copy to directory for future use in overlays?
It would also have to name the .png's after each user it's pulling from.
I have a database at zoho creator. They feed me a json of the database content. I have trouble to parse and display that data with jquery or php or in html
Question : So how do I capture json data, and save (convert) it to file as XML. With the xml file I can parse it with jquery xpath easily... the "file" will be a local database, as a backup (if saved)
anybod have clue on that ?
as request.. here is the link for the query -link-
getting a way to display data from var i need is the minimum i must have !
like prod_categorie or prod_nom
note :
i can get help with any tutorial on
how to get xml data from zoho
any json to xml converter (jquery)
out there ?????
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div id="Liste_output"></div>
<script type="text/javascript">
jQuery.ajax({
url: "http://creatorexport.zoho.com/marcandremenard/application-lemieux/json/Liste_produits_View1/7GWhjVxYeNDePjPZnExCKy58Aqr21JX2hJEE6fAfgfkapEQnRjRd5RUy8wdjKuhmFEhJR9QRsBCUBjACAdSgmJNQSvxMt6geaMNC/",
dataType: "json",
success: function(data) {
var Liste_div = jQuery("#Liste_output");
var Liste_data = data["Liste_des_produits1"];
for (var i=0; i<Liste_data.length; ++i) {
var prod_i = Liste_data[i];
Liste_div.append('<div>' +
'<div>Nom: <span>' + prod_i["prod_nom"] + '</span></div>' +
'<img src="/images/prod/'+ prod_i["prod_photo"] +'"/>' +
'<div>Description: <span>' + prod_i["prod_desc"] + '</span></div>' +
'<div>Ingredient: <span>' + prod_i["prod_ingredient"] + '</span></div>' +
'<div>Odeur: <div class="odeur_cls"></div></div>' +
'<div>Certification: <div class="cert_cls"></div></div>' +
'</div>');
var odeur_data = prod_i["prod_odeur"];
for (var j=0; j<odeur_data.length; ++j) {
jQuery('#Liste_output odeur_cls').eq(j).append('<span>' +
odeur_data[j] + '</span>' + (j<odeur_data.length-1 ? ', ' : ''));
}
var cert_data = prod_i["prod_certification"];
for (var k=0; k<cert_data.length; ++k) {
jQuery('#Liste_output cert_cls').eq(k).append('<div>' + cert_data[k] + '</div>');
}
}
}
});
</script>
</body>
</html>
This will not work from a local file. The HTML must be served from the same domain as the database query, that is, it must be served from http://creatorexport.zoho.com (you can put it in the app subfolder)
– OR –
You must read the zoho docs and find out how to do a "callback" (sometimes called "JSONP"). Usually this is done by adding something like ?callback=data to the end of the URL.
Firstly, Javascript has no file-output capability. The best it can do is send data back to a server for processing there -- so the "capture json data, and save it to file as XML" idea is out.
What problems in particular are you having with using JSON? As it gets converted to a native Javascript object, I find it quite easy to work with myself. Though, I can see that if you wanted to use XPath to query it, JSON is no help. You should still be able to get to whatever data you need, but it might be a bit more verbose.
In your example JSON:
{"Liste_des_produits1":[{"Added_Time":"28-Sep-2009 16:35:03",
"prod_ingredient":"sgsdgds","prod_danger":["sans danger pour xyz"],"prod_odeur"..
You could access the prod_danger property like this:
$.getJSON(url, function(data) {
var danger = data.List_des_produits1[0].prod_danger;
});
If you are having trouble getting the right path to a property, Firebug is a great help with this. Just call this:
$.getJSON(url, function(data) {
console.log(data);
});
...and then you can browse through its properties in a tree-structure.
There are jQuery pluggins for such convertion, for example json2xml.