javascript method not working - javascript

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"

Related

Javascript redirection not working in Flask

I am building a flask website and am trying to make a search bar that is always on the top menĂ¹, I would have liked to handle it in the Python backend but I could not find a way to do that without including whithin each backed page the code to handle it (which if it is the only way is fine) so I decided to try making it work with JavaScript. This is my code (without the parts which I found unrelated to the problem):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<input type="search" id="searchbar"/>
<button id="goto">Search</button>
</form>
<script>
document.getElementById("goto").addEventListener("click", goTo);
function goTo()
{
var result = document.getElementById("searchbar").value;
window.location.href = "/users/"+result;
}
</script>
</body>
</html>
What it is supposed to do is redirect me to "http://myip/users/WhatItyped" while it just adds "/?" to the end of the URL, any idea of why this is?
Update: I found out that if I add an alert before defining result it works
Try using window.location.pathname
JavaScript Window Location states href points to the full URL, including protocol & hostname. Since you are not changing either of those, you can just change the relative path from the root using pathname.
This has also been answered before:
How can I extract and then change the url path using javascript?

My HTML file won't link with my Javascript file

I am trying to complete an exercise for one of my courses and my HTML file won't link with my Javascript file. I put the link between my HTML file and my Javascript file in the body of my HTML file but the files still won't connect. When I test this code in Microsoft Edge, the buttons simply do not work. Anybody know what the problem is?
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Page</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<button onclick = "startWorker()">Start Worker</button>
<button onclick = "stopWorker()">Stop Worker</button>
<ul id = "output">
</ul>
<script type = "text/javascript" src = "/js/script.js"></script>
</body>
</html>
Javascript
var worker;
function startWorker(){
worker = new Worker ("js/mod4_worker.js");
worker.onmessage = function(event){
document.getElementById("output").innerHTML += '<li>' + event.data + '</li>';
};
}
function stopWorker(){
worker.terminate();
}
Files
So, I would try my comments :
Change the script.js path to : "../js/script.js"
Change the worker passed script to "../js/mod4_worker.js"
As GGG said, using a path starting with "/", a slash, use the path from root. The full path is either :
Windows : file://DriveLetter:\REST_OF_PATH
Unix/Linux/OSX : file:///REST_OF_PATH
WebServer : http://domain/REST_OF_PATH
If the structure is from /webapp/ :
html/index.html
js/script.js
Accessing script.js from index.html needs to go back one folder (..) and then set the path seen here (js/script.js) which gives (../js/script.js) OR using full path (/webapp/js/script.js) which I wouldn't recommend because if you change "webapp" directory of location or URL (on WebServer)
Remove the / from your src in the index.html. So it should be
src = "js/script.js"
Why? When you begin the src value with a /, that means you're referring to an absolute path (in other words, it starts the path from your drive's root). My devtools shows it as
file:///C:/js/script.js
By removing the first / in your src, you're now doing relative pathing, and it will look in the correct place.
Permissions & File locations
(Stumbled on this Q and here's the only way I solved it...)
For me, I found it was a permissions and file location issue...
I'm running a local webserver on Ubuntu 18 Desktop, working with dev from a local folder linked to the web directory: /var/www/html/MY_DEV -> /home/me/MY_DEV. So, the www-data user couldn't actually "own" them like it needed to.
I use this setup just fine for PHP, HTML, and CSS just fine. But, if I include a javascript file via src="", no matter what I do, it doesn't work.
The only way I could get it to work on my desktop is if BOTH the served file (somefile.php or somefile.html) are physically at /var/www/html/...
And, of course accessing them at localhost/...
And, of course owning them obsessively with sudo chown -R www-data:www-data /var/www/html

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.

HTML/Javascript - Get image source from online file

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. :)

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