HTML/Javascript - Get image source from online file - javascript

I want to have an image in a webpage that can be changed based on the filepath stored in a file online (it doesn't matter what typer of text file - xml, .txt - whatever works best).
So I basically want to have the page retrieve the text from that file, and then use that text as the source for an image in that page.
I'm assuming this is a Javascript thing, but it doesn't matter to me, as long as it works.
Any ideas?
Thanks!!
**Edit: Forgot to mention: I'm using the code in a Google Chrome Extension, not sure that matters, as it uses regular HTML/Javascript, but it's stored on the users computer, and I want the image to be stored on my server.
**Edit2:
Just got something that seems to work very well, and I only need this in the body part of the code:
<script type="text/javascript" >
var i=0;
for (i=0;i<=FilePath.length - 1;i++)
{
document.write('<img src="' + FilePath[i] + '"/>');
}
</script>
Hope this is valid code, but it definitely seems to work here...

Its simple store the filepaths in a Javascript file , create an array in the JS file , and include all the filepaths in the array, then store the file on the webserver .
Then after that you can retrieve it using
<script src="JS_File_path_on_web_server" type="text/javascript" ></script>
After you retrieve it , you can use Javascript , I prefer jQuery , to replace the src attribute on the Image with the one from the array .
EDIT : Full version :
//Javascript web server File
var FilePath=new Array("Path1","Path2","Path3");
Create a file like this and store as many paths as you want in the array .
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
<script src="JS_File_path_on_web_server" type="text/javascript" ></script>
<script type="text/javascript" >
$(document).ready(function()
{
$('#DisplayImage').attr('src',FilePath[0]);
});
</script>
</head>
<body>
<img src="" id="DisplayImage" />
</body>
</html>
This is a simple example , you can try learning javascript and Jquery to tweak it further .

Since my php based answer was not applicable, we can all ignore it now. :)

Related

how do i import a html form into a separate file

I've been trying to import a html form and embedded it into a separate html file, my javascript to try and upload the file containing the form looks like this
<link rel="import" href="formhtml5.html" onload="handleLoad(event)"
onerror="handleError(event)">
var link = document.querySelector('link[rel="import"]');
var el = link.import.querySelector('#flexyForm');
document.body.appendChild(link);
however when I try and see if the form is uploaded my page is just blank? been struggling with this for days now and its driving me nuts, anyone got any guesses to see how it works?
If this is what you're looking for, it's possible with jQuery.
firstFile.html
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includeForm").load("formFile.html");
});
</script>
</head>
<body>
<div id="includeForm"></div>
</body>
</html>
formFile.html
<p>This is my Form</p>
Note: Your question is not clear, you're not uploading anything. Instead you're just importing some lines of code from another html file to yours. If yes, above code should work fine!
Also, If the included HTML file has CSS attached to it, it might mess up your page style. So better to do internal CSS or change the CSS external link in formFile as per link rules of firstFile.html
You can also use php in additional to JS to get the content of the second file.
<?php file_get_contents="path to your file here" ?>

Html code to Png image

I made a web application which allow the user to create an image dynamically in JavaScript.
It use jQuery to allow the user to place div, resize them and drag them into a <div> Container.
When the user finished to place all div, he can press the "Generate" button which send the <div> Container outerHTML code into a local database.
Then the user can use another script, in php, and past in parameter the id in the database of which render he want to display, then the php script create a page using the code in the database.
My problem is now I want to take the code of this generated html page, then convert it into a png image.
I looked at some other posts and found something interesting : Phantom.js
But what I tried doesn't seem to work. Here is my code :
<html>
<head>
<title>Test</title>
<LINK rel='stylesheet' type='text/css' href='style.css'>
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
</head>
<body>
<script>
var page = require('webpage').create();
page.open('http://10.237.35.10/maxime/affichage.php?afficheur=0', function() {
page.render('affichageTest.png');
phantom.exit();
});
</script>
</body>
</html>
So we have the database with the div outerHTML code contained at the id '0'.
"affichage.php" take in parameter a variable "afficheur" then it ask the database to get the code from this variable. For example, afficheur=0 will return the div code contained in the database at the id=0.
When I go to "http://10.237.35.10/maxime/affichage.php?afficheur=0" I have a html page with the render I want. But when I try to run the script I'd posted higher, I haven't any "affichageTest.png" rendered in my folder.
What do I have to do? Do I have to import anything else to run Phantom.js? Or maybe I need to add something to my code?
PhantomJS is a binary not a javascript librarie (it is actually a headless webkit), I can not test it here atm, but here the main idea :
First download the PhantomJS binary, upload it somewhere and make it executable (chmod +x).
Create a file named test.js with this code below :
var page = require('webpage').create();
page.open('http://10.237.35.10/maxime/affichage.php?afficheur=0', function() {
page.render('affichageTest.png');
phantom.exit();
});
Create a file named display.php with this code below :
<?php
$file_path = exec('/path/to/phantomjs test.js');
?>
<html>
<head>
<title>Test</title>
<LINK rel='stylesheet' type='text/css' href='style.css'>
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
</head>
<body>
<img src="<?php $file_path ?>" alt="test">
</body>
</html>
Visit the display.php page to see the screen capture
If you need a full script solution, as you have said in comments, your only hope is Image Magic php extension. This in conjunction with HTML2PDF can be used to device html to image conversion for non-complex markup.
The trick is to create a pdf out of html first:
$html2pdf = new HTML2PDF('P', 'A4');
$html2pdf->writeHTML($html_content);
$file = $html2pdf->Output('temp.pdf','F');
Now you can get this pdf file and convert it image using Image Magic
$im = new imagick('temp.pdf');
$im->setImageFormat( "jpg" );
$img_name = time().'.jpg';
$im->setSize(800,600);
$im->writeImage($img_name);
$im->clear();
$im->destroy();
Installation of Image Magic extensions and support libraries could be painstaking. Please read the installation notes carefully.
The complexity of the html markup which could be converted is limited. You can do a fairly good job. But you can't call it a day if you need to convert ANY html.

javascript method not working

this code is not working as expected
<html>
<head><title>alert()</title>
<script type="text/javascript">
function greeting()
{
var name=prompt("what's your name?","your name");
if(name){
alert("hi, " + name + " welcome to this page");
document.getElementById("im").src="F:\wallpapers\a.jpg";
}
}
</script>
</head>
<body onload="alert('hi, this is the alert() function');">
<img id="im" src="F:\wallpapers\Ubuntu_wallpaper__1_by_leroi14.jpg" onclick="greeting();" /></body>
</html>
document.getElementById("im").src="F:\wallpapers\a.jpg" is not displaying the image when given absolute path.
But it works if image is in same folder as this file.
can anyone help?
For whatever reason you use backslashes in your path, which need to be escaped in string literals:
"F:\wallpapers\a.jpg" === "F:wallpapersa.jpg"
Use "F:\\wallpapers\\a.jpg" or "F:/wallpapers/a.jpg" instead.
If you plan on serving this page to others, you don't want to use an absolute path. Javascript runs on the browser, and does not have access to the server's filesystem for absolute paths.
See answers here
It's common to have an images folder within your website's project folder. Put images in this folder, then you can use src="/images/a.jpg"

How to make an external javascript file knows its own host?

Is there any way that in an external javascript file, can know the host of the file?
For example, if I have the site http://hostOne.com/index.php, the code of the file index.php:
<html>
<head>
<script type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
I need that in the file test.js can know the host http://hostTwo.com.
Thank you.
EDIT
or it can know the tag "script" which was called?, with this option I can analyzes the tag and get the "src" attribute. But I don't want to depend on the name of the file test.js and analyze all the tag script that contains the site.
*Solution based on the code of #Armi *
Html:
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script id="idscript" type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
code in JS
var
url = $('head').find('#idscript').attr('src'),
host = url.replace(/(\/\/.*?\/).*/g, '$1');
console.log(host);
I've got an idea (the snippet based on jQuery):
var yourScriptTag = $('head').find('script[src$="jquery-1.7.1.js"]').eq(0);
var theHostnameOfYourScript = $(yourScriptTag).attr('src').replace(/(http:\/\/.*?\/).*/g, '$1');
alert(theHostnameOfYourScript);
jsfiddle example: http://alpha.jsfiddle.net/XsJn8/
If you know the filename of your script (and if this is always the same and unique) you can use this snippet to get the hostname.
If this path is relative (and contains no host) you can get the hostname with a simple location.hostname
Sorry, not possible. The content of the script is downloaded and after this it is fired. At this point the script "thinks" he is at your site.
Of course unless the host is hardcoded in the script.
This is not possible, because the JavaScript code is executed client-sided. You could propably parse it somehow out of your URL but, I don't think either that this is very useful and possible.
Inside test.js, you can use :
var url = document.URL;
then parse the url result.
You can't make cross-site scripting, so if you need more sophisticated stuff, you could write your javascript in php and call :
<script type="text/javascript" src="http://hostTwo.com/script/test.php"></script>
But that's not standard.
Anyway,, the solution is on the server, with a designed proxy.

Relative Paths in Javascript in an external file

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

Categories