jQuery: how to get a random number in filename - javascript

I'm using the following code to get a html content file from a folder.
$(window).bind('load', function() {
$.ajax({
url: "/folder/htmlcontent1.html",
success: function (data) { $('.attach').append(data); },
dataType: 'html'
});
});
I want to make it random and pick up a random file on every page load. The files will be named incrementally like "htmlcontent1,htmlcontent2". I wonder if it's possible to use Math.floor in the url path like this:
var rand_no = Math.floor((3-1)*Math.random()) + 1;
$.ajax({
url: "/folder/htmlcontent' + rand_no + '.html",
success: function (data) { $('.attach').append(data); },
dataType: 'html'
});

Yes, it's possible. But you must fix the quotes :
url: "/folder/htmlcontent" + rand_no + ".html",

Related

Download Base64 image through javascript

I am working on an image panel that displays the image titles and a link to download the image. I have an onclick function that gathers the base64 data from the database and then 'decodes' it. However, when I decode it I'm getting back a string of Chinese text..which is obviously not what I'm looking for.
$(document).ready(function() {
$('.downloadAttachment').on('click', function() {
var documentId = $(this).attr("data-id");
console.log(documentId)
$.ajax({
dataType: 'json',
//data: id,
async: false,
type: 'GET',
//url: baseUrl + 'rest/incdDocument/getAll?branchCode=' + brCode + '&receivedDate=' + receiveDate + '&complaintID=' + cId + '&incidentID=' + incidentId+ '&documentID='+documentId,
url: baseUrl + 'rest/incdDocument/get?branchCode=009&receivedDate=03/10/2017&complaintID=170&incidentID=3'+'&documentID='+documentId,
success: function(data) {
if (data) {
var image = Base64.decode(data.data);
window.open(image, '_blank');
}
},
error: function(request, status, error) {
console.log(error)
}
});
return false;
})
});
Is there a better way to extract this data and actually turn it into an image?
Searching for like this ?
var image = new Image();
image.src = data; (complete base64 sting with imagetype)
Download Image
Make a download.php file with return the a image with
header('Content-type:image/png'); or other image type

How to strip a string from unwanted parts?

Given an url like this:
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg
How do i get it to be like
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,44_AL_.jpg
The issue I am having is with retrieving IMDB poster images, using this:
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: form.serialize(), // assuming the form has a hidden input with api_key name, containing your API key
crossDomain: true,
dataType: "jsonp",
success: function(data) {
window.console.log(data);
}
});
});
I get a json response like:
"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw##._V1_UX32_CR0,0,32,44_AL_.jpg"
I get no poster and the api i am using don't help, yet that thumbnail image is including various formats, one of which is 44_al which is what i would like to leave as a string in order to output it like:
function imdbLoad() {
var form = $("#usp-title").val();
var encodedTerm = encodeURIComponent(form);
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
q: encodedTerm
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
$.each(data.data.results, function(i, items) {
$("#imdb").append('<h2>'+i+'</h2>');
$.each(items, function(k, item) {
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ item.thumbnail +"'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
});
});
}
});
}
Unless anyone has any other way to grab the poster url
You can either use regex to replace string part that is not required
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var regex = /,.*(?=,)/g;
console.log(url.replace(regex, ''))
or split using comma(,) and join first and last part.
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var parts = url.split(',');
console.log(parts[0] + ',' + parts.pop())
This is a bit of a longer code as I have included few bits such as limiting the number of results but basically what I noticed is that after the ## the whole string is about image size. So instead of using a regex (that would be the answer for this specific question), I could simply add the dimension to the url as a string like:
<img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'>
Full code
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
api_key: "...",
q: form.find('input[name="q"]').val()
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
var thumbnailMod, limiteRes = 1;
if (data.data.results.titles !== undefined) {
$("#imdb").append('<h2>Titles</h2>');
$.each(data.data.results.titles, function(i, item) {
thumbnailMod = item.thumbnail.split('#.');
if (thumbnailMod.length > 1) {
if (limiteRes > 3) {
return;
}
limiteRes++;
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
}
});
} else {
console.log('No titles found for this search.');
}
}
});
});

Using document.currentScript to append data to divs

I want to append data into divs by passing their id as attributes in a script tag. In this example the first-div should get get 'test1' appended to it, and the second-div should get the 'test2' appended to it.
However, the result it that both 'test1' and 'test2' are appended to second-div. first-div is empty. I'm guessing it has to do with how document.currentScript is functioning. Is there any way to get the result I am looking for?
<div id="first-div"></div>
<div id="second-div"></div>
<script attr1="name1" attr2="name2" to-div="first-div" type="text/javascript">
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test1");
});
</script>
<script attr1="name3" attr2="name4" to-div="second-div" type="text/javascript">
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test2");
});
</script>
Also, in the solution, the scripts cannot have id attributes, which is why I am trying to use document.currentScript.
The reason for this is that the code will be hosted on my servers. The code will append information into the divs the user wants, given parameters passed through attributes on the script tag. In the end the user should be able to use:
<script attr1="var1" attr2="var2" to-div="custom-div" src="http://www.myurl.com/assets/script.js" type="text/javascript"></script>
To insert data into their custom-div based on code I run on my servers dependend on the parameters attr1 and attr2 they provide.
Your problem is that var append_div is a global variable and each time a new script tag is encountered it gets overwritten with the new value.
Since ajax is asynchronous , by the time the responses return the other script tags will have been evaluated so append_div will have the value of the last script tag.
You could fix this by creating a function that wraps the ajax
function doAjax(elementId, attr1) {
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function (data) {
$('#' + elementId).append("test2");
}
});
}
doAjax(append_div, attr1);
An even better solution as pointed out by #Rhumborl is to use an IIFE
(function( elementId, attr1){
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function (data) {
$('#' + elementId).append("test2");
}
});
}(elementId, attr1);
Or wrap all of your code in an IIFE and no arguments would need to be passed in.
(function(){
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test2");
}
});
}();

Parsing json synchronously from url in javascript

I'm trying to get title of a youtube video. So i'm using jQuery to parse json. But it works asynchronously, so the answer comes after the page loaded. The result is:
http://www.youtube.com/watch?v=Ym0hZG-zNOk (undefined)
How can i fix it?
Thanks.
http://jsfiddle.net/3vQht/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
document.writeln("<a target='_blank' href='" + link + "'>" + link.bold() + "</a> (" + name(videoID) + ")<br>");
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc&callback=?";
var fin;
$.getJSON(source, function(json) {
fin = json.data.title;
console.log(fin);
});
return fin;
}
</script>
</head>
<body>
</body>
</html>
Hy,
here is the solution :)
<script type="text/javascript">
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc";
$.ajax({
type: 'GET',
url: source,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
$(document).ready(function() {
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
name(videoID);
});
</script>
If you want to get your data sync just use this version:
$.ajax({
type: 'GET',
url: source,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
getJSON is asynchronous, so when the return fin; is reached, the data hasn't been fetched yet.
Everything that depends on the JSON MUST be inside the success callback.
If you prefere, you can also fetch your data synchronously. Check the jQuery.ajax() documentation for the async parameter.
EDIT: Just figured that you're loading your data using JSONP and that it's not possible to do that synchronously. You need to use asynchronous callbacks instead.
I haven't played with their api, but a quick look at
https://developers.google.com/youtube/2.0/developers_guide_json
indicates that they support jsonp callbacks so that you can prepend a script that does sends the data to a callback function (just add &callback=yourFunction to the end of the url)
function prependScriptFromUrl(s){
var a=document.createElement("script");
var b=document.getElementsByTagName('head')[0];
a.src=s;
b.insertBefore(a,b.firstChild)
}

jQuery form plugin: field value serialization

I'm used to send passing data with the jQuery form pluging using data: $("form#myform").serialize(). It doesn't make sense to create separate forms in my current case, since there are only two fields. Hence I created the following function:
function storeNotificationMessage(name) {
var content = $("textarea#" + name).val();
var id = $('#id').val();
content = encodeURI(content); // tried this
content = escape(content); // and that
$.ajax({
async: false,
data: "entry=" + id + "&name=" + name + "&msg=" + msg,
type: 'post',
url: '?url=updateEntry',
success: function(response) {
done();
}
});
}
Unfortunately neither encodeURI nor escape work correctly for special characters like ' or + or German umlauts.
Question: what is the proper way to encode text values?
Don't use escape nor encodeURI nor + when dealing with urls. Simply leave all encoding to jquery:
function storeNotificationMessage(name) {
$.ajax({
async: false,
data: {
entry: $('#id').val(),
name: name,
msg: $('textarea#' + name).val()
},
type: 'post',
url: '?url=updateEntry',
success: function(response) {
done();
}
});
}
Remark: using AJAX with async = false makes very little sense and should be avoided.

Categories

Resources