I would like to display the (result) of the below code in base64.
The below code shortens inputted url and display its bitly result but i want it to encode the result in base64 instead.
i.e it would have shortened the inputted url to bitly in hidden but will display only the base64 encoded result.
For example, if a particular shortened url result is
http://bit.ly/url
it should display
aHR0cDovL2JpdC5seS91cmw=
jQuery
$(document).ready(function() {
//bit_url function
function bit_url(url) {
var url=url;
var username="username"; // bit.ly Api username
var key="BitLy Key"; //bit.ly Api key
$.ajax({
url:"http://api.bit.ly/v3/shorten",
data:{longUrl:url,apiKey:key,login:username},
dataType:"jsonp",
success:function(v) {
var bit_url=v.data.url;
$("#result").html(''+bit_url+'');
}
});
}
$("#short").click(function() {
var url=$("#url").val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var urltest=urlRegex.test(url);
if(urltest) {
bit_url(url);
} else {
alert("Bad URL");
}
});
});
HTML
Enter URL:
<input type="text" placeholder="http://"" name="url" id="url"/>
<input type="submit" id="short" value="Submit"/>
<div id="result"></div>
Would appreciate any help.
You should be able to use btoa() to encode the bit.ly urls. Something like this would work:
$(document).ready(function() {
//bit_url function
function bit_url(url) {
var url=url;
var username="username"; // bit.ly Api username
var key="BitLy Key"; //bit.ly Api key
$.ajax({
url:"http://api.bit.ly/v3/shorten",
data:{longUrl:url,apiKey:key,login:username},
dataType:"jsonp",
success:function(v) {
var bit_url=v.data.url;
var encodedUrl = btoa(bit_url);
console.log(encodedUrl);
$("#result").html(''+bit_url+'');
}
});
}
$("#short").click(function() {
var url=$("#url").val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var urltest=urlRegex.test(url);
if(urltest) {
bit_url(url);
} else {
alert("Bad URL");
}
});
});
More information on encoding and decoding base64 in JavaScript is available in the developer docs here:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
Hope that helps!
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
<script type="text/javascript">
$(document).ready(function() {
var chanName = "";
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//MAKE IT TO A VAR
});
}
function loadChannel(data) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
}, 5000);
$('#update').click( function(){
loadchannelID($('#chnlName').val());
})
});
</script>
This is what is have done so far. I need to get the id form a Youtube channel but i have a Youtube name. So i need to convert the name to the youtube channel id. The "Function loadchannelID" is what i have so far, it works but i need to get the #ytID to a var. But I dont know how to do that. The other function is to show the data from the Channel ID and that will work aswell if the id is converted to a var. Please help! Thanks!
I hope this is what you want to achieve:
var chanName = "";
var chanID = 0;
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
chanID = data.items[0].id;
$('#ytID').html(chanID);
loadChannel(chanID); // now, you know the ID, pass it to "loadChannel"
});
}
function loadChannel (id) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
I am not clear if you are trying to get the value or you try to make the url but in both cases you can do:
if you want to get the param value you can use:
var url_string = "https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=Pewdiepie&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI";
var url = new URL(url_string);
var forUsername = url.searchParams.get("forUsername");
if you want to set the param you can do:
var forUsername = url.searchParams.set("forUsername", yourValueHere);
As ive already said, your code is async, so you may use Promises like this:
function loadchannelID(name){
return new Promise(function(resolve){
var chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//lets resolve the promise
resolve(data.items[0].id);
});
});
}
So you can use it like this:
loadChanelID("test").then(function(name){
alert("name is"+name);
});
If you change
function loadChannel(data) {
To:
function loadChannel(id){
You can do:
loadChanelID("test").then(loadChannel);
I assume you want to use your var within the class and chanName is your channel ID and name container array
(function($, jsYouTube){
var chanName = "";
$.getChannelID = function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$this.chanName['id'] = data.items[0].id ;
});
}
})(jQuery, 'jsYouTube');
I am trying to open new window using window.open(actionUrl)
the actionUrl is compose form the action address and url as parameter.
so eventually the actionUrl is :
"/Default/Details?url=http://www.someaddress.com?a1=1&a2=2&a3=3"
However in the action the url i get is :
"http://www.someaddress.com?a1=1"
I do not get "&a2=2&a3=3" parameters
Here is the relevant view code:
<div>
<input type="button" value="test" id="btnTest" />
</div>
<script>
var vurl = '#Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + url;
window.open(vurl);
});
})
</script>
and this is the controller and action
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
// GET: Default/Details/5
public ActionResult Details(string url)
{
return View();
}
}
You need to use the encodeURIComponent function on the url parameter's value:
var actionUrl = '/Default/Details?url=' + encodeURIComponent('http://www.someaddress.com?a1=1&a2=2&a3=3');
The &a2=2&a3=3 part was actually part of the /Default/Details URL, not the http://www.someaddress.com one. Now that the inner URL is URI encoded, it should work.
Make sure to decode the value when using the url parameter though, using decodeURIComponent:
var urlMatch = location.search.match(/url=(.*)&?/);
if (urlMatch) {
var decodedUrl = decodeURIComponent(urlMatch[1]);
// do something with the decoded URL...
}
EDIT
For the first part (URI encoding) and based on your code, you should use it this way:
<div>
<input type="button" value="test" id="btnTest" />
</div>
<script>
var vurl = '#Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + encodeURIComponent(url);
window.open(vurl);
});
})
</script>
As for the ASP.NET part and the use of the string url parameter, I'd suggest checking the following post: using decodeURIComponent within asp.net as I'm not familiar with this environment.
This question already has an answer here:
Reading local files with <input type="file">? [duplicate]
(1 answer)
Closed 8 years ago.
I want to get and read a JSON file that would be uploaded by the user.
I created the html input file:
<div id="button_open" class="button">
<span>Open a JSON file</span>
<input id="input_open" class="input_file" type="file">
</div>
And now, I don't know how to load the data from the file. I only can get the filename.
Here is what I wrote:
$(document).ready(function(){
$("#input_open").change(onOpenChange);
})
function onOpenChange(e) {
var filname = $("#input_open").val();
var fileContent = ... ?
var jsonData = JSON.parse(fileContent);
}
Anyone knows how to get the file content?
<script>
$(document).ready(function(){
$("#input_open").change(onOpenChange);
})
function onOpenChange(e) {
var filname = $("#input_open").val();
var fileContent = getTxt();
var jsonData = JSON.parse(fileContent);
}
getTxt = function (){
$.ajax({
url:'text.json',
success: function (data){
fileContent =data;
return data
}
});
}
</script>
Here is the solution I get with the help of Ameen:
$(document).ready(function(){
$("#input_open").change(onOpenChange);
})
function onOpenChange() {
var filePath = $("#input_open").val();
var startIndex = filePath.indexOf('\\') >= 0 ? filePath.lastIndexOf('\\') : filePath.lastIndexOf('/');
var filename = filePath.substring(startIndex);
if(filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
$.ajax({
url: filename,
success: onOpenLoad
});
}
function onOpenLoad(fileContent) {
var data = JSON.parse(fileContent);
// do something with the data
}
The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request
I want to make a RuneScape(an MMORPG Game) Name Checker. For this i am using an IRC bot. The URL i am using to check names is this- http://rscript.org/lookup.php?type=namecheck&name=
I am using javascript to take input and go to this url for checking names. The code i am using is this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
}
</script>
</head>
<body>
<input class="textBox" id="uname" type="text" maxlength="15" required/>
<input type="button" onclick="nameCheck()" value="Submit">
</body>
</html>
To proceed with this i need a code that could check the output of the final url created ie.
curl. If the output page looks like this:
START
NAMECHECK: NOTAVALIBLE
SUGGESTIONS: blah blah blah
END
Then the code should run the function nameNotAva(). And if the output is like this:
START
NAMECHECK: AVALIBLE
END
Then the code should run the function nameAva().
The question:
I just want that using javascript the output be evalutaled to check that if NAMECHECK: NOTAVAILABLE is a part of the output page or not. If yes then a function nameNotAva() should be run. Otherwise a function nameAva() should be run.
Dont know what language u are using, with jQuery u can do following things
You can load the response inside a div.
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
var output = $('#someDiv').load( curl ).html() // .html() will give you the output or what the page
if( output.contains('NAMECHECK: NOTAVALIBLE'){ nameNotAva(); }
}
You can use simple AJAX and get the response text ( may be with async false)
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
$.ajax({
url : curl,
type : 'GET' //or 'POST',
success : function( urlOutput ){
if( urlOutput .contains('NAMECHECK: NOTAVALIBLE'){
nameNotAva();
}
}
});
}