js function does not work when invoked externally - javascript

I know this is silly but i think i cant crack it for last couple of hours.
I am writing to understand how this works.
I have a simple js function that i want it to be kept in an external file and it just dont work when invoked from my .php file.
Here is the setup:
I have 4 separate php files like register.php, dashboard.php, header.php, actions.php
I have defined some functions in my script.js like below
function fn1(){
alert("fn1");
}
function fn2(){
alert("fn2");
}
function fn3(){
alert("fn3");
}
Now, I have defined in my header.php to include this script file as
<!doctype html>
<html>
<head>
...
</head>
<body>
<script src='/js/script.js'></script>
</body>
...
I include this header.php in my other php files like
<?php include('header.php'); ?>
<script language="javascript">
fn1();
</script>
This does not work. It says ..
SyntaxError: syntax error script.js:1
ReferenceError: fn1 is not defined dashboard.php
Is there something wrong in the way i setup and distribute them into separate files ?
The same function if i locally define in these php files separately, it works fine.
So its a problem only when invoked from an external js script.
Please suggest what am i doing wrong.
I have bunch of functions that i wrote earlier which works fine but i want to understand this first so that i can go on with moving those functions in the same way to keep them global.
What i want to acheive ?
I have PHP files based on the view/actions as follows ..
login.php
register.php
dashboard.php
useraction.php
header.php
there are several div's like my navbar, footer, sidebar that are common to all these php's;
header.php has all the required js functions to load these div's based on various conditions and events;
My plan is to include header.php in all my php's so that all the functions defined in it are included too in every php file and the common div's are
loaded by the header.php itself.
Does it make sense ? Is this the right way to achieve this? If not, how do i do, please clarify.
So as per this plan, i attempted making a simple js function that can be kept in an external js to be called from these php which did not work

language is deprecated. You should just use <script> tags.
The problem is with your first line, you should post that, the posted code works fine, I just tested it. It's probably a syntax mistake.
Still, you should consider loading the scripts in a different php file than the one that takes care of setting up the header and the navbar or what have you.
Edit:
Sorry, I said probably a syntax mistake, when it clearly is just that:
SyntaxError: syntax error script.js:1
Delete the first line of your 'script.js' and it should work.
This got it working for me:
header.php
<!doctype html>
<html>
<head>
</head>
<body>
<script src='script.js'></script>
main.php
<?php include('header.php'); ?>
<script>
fn1();
</script>
script.js
function fn1(){
alert("fn1");
}
function fn2(){
alert("fn2");
}
function fn3(){
alert("fn3");
}
Edit 2:
Suddenly, this seems more a php question.
Your scripts should probably be loaded in a separate php file, scripts.php, that you include in the bottom of a specific php page, but just before opening the <script> tags, if there is need for particular js on that page.
This makes for a faster page loading. You could, though, include specific scripts in the header part, even in the document's <head>, but you should try to keep those scripts lightweight, so they don't heavily delay the user.
You can include php's anywhere. For example, this could be dashboard.php:
<?php include('header.php'); ?>
<div id="ImOnlyOnThisParticularPage"></div>
<!-- Footer loads scripts after the <footer> or divs that it contains -->
<?php include('footer.php'); ?>
<script>
var iOnlyDoSomethingInThisPage = function()
{
console.log("debug");
}
</script>
</body>
</html>

#param LoL i replicated your code and kept it in separate files and i am getting the alert as expected .In case you have issues open your console panel and try debugging.Press F12 and check for console related errors mostly u don't have your files are correct path

Related

Why can't I attach javascript to my html?

No matter how I choose to add a javascript file to a html file, it doesn't seem to work. My original code is longer and has more stuff in it but I thought I would isolate the problem and see if with a very basic bit of code I would get the same problem (which I do).
I've tried adding the script tag to the head and to the body (at the start and at the end).
Brackets states that the function is never called and also seems to think that alert doesn't exist. If I add internal javascript it works.
in Chrome's console it reads:
test.html:1 Uncaught ReferenceError: helloWorld is not defined
at HTMLButtonElement.onclick (test.html:1) onclick # test.html:1
when I click the button.
HTML is:
<!doctype>
<head>
<title>testcode</title>
<script src="test.js"></script>
</head>
<body>
<button onclick="helloWorld()">Press to say hello world</button>
</body>
test.js is in the same folder and is:
function helloWorld() {
alert("Hello World!");
}
UPDATE: I changed nothing and just reopened the browser, now it works (currently missing python a lot).
The code is working for me. Maybe it's the path of the files. If the files are in the same level, it should works..
- index.html
- test.js
But if the script is in a folder, you should change the script tag. Exemple :
- index.html
- /js
- test.js
<script src="js/test.js"></script>
There is another case, if your html page is /article/hello and your js /test.js you should change the script tag with <script src="../test.js"></script>
It's working for me. I just copied and pasted your exact code and it was working for me. Make sure you have saved both html and js files in same directory.
In order to check if JS file is included just open Developers Options (Ctrl+Shift+I) in chrome and then see if you get any error like this(in case js file was not included)

Adding a JavaScript embed to HTML

I am given this code which should display an embedded small coupon version of this page https://weedmaps.com/deals#/1118217:
<script type="text/javascript">var coupon_id = 17811;</script>
<script type="text/javascript">var coupon_type = "deliveries";</script>
<script type="text/javascript" src="https://weedmaps.com/embed/coupon.js"></script>
I do not know how to add the JavaScript to the HTML correctly. I have placed the following scripts in the head section. But I don't understand how to have the coupon generate in the div I want it to. I have tried calling the JavaScript function, but I've never worked with JavaScript before. Could someone please help me embed this coupon.
I've taken a look at your script and first of all: it definitely should be placed inside the document and not into the <head> section because coupon.js is writing out html at the placement of the coupon.js script import.
In theory you just need to place the script and it should work but there are some problems:
You need to execute it on a web server - when running as a plain html file the script just tries to find the libraries in your file system which does not work.
It still would not work because it would still try to find some resources at your web-server. In mycase it the script tried to load http://localhost:63342/restpoints/deliveries/17811/deal which will not work
To prove 2. just try https://weedmaps.com/restpoints/deliveries/17811/deal with the correct domain. Then you are receiving correct JSON which is used to fill the coupon pane.
=> Consequently the script you were given has problems if it should be executable from domains different from "weedmaps.com"
Javascript can be between head tag but it advisable to put it below before the body closing tag, to allow your page contents loads first before loading javascript. Just import your javascript. and call out. Hope this was helpful.
<!DOCTYPE html>
<html>
<head>
</head>
var coupon_id = 17811;
The JS indicates it is looking for an element with an id of #weedCouponPane. Do you have this in your html? i.e.
<div id="weedCouponPane"></div>

Java script doesn't work on an external sheet but it works on the main html file. Why is that and how do I fix it?

Here is my first main html code
Main HTML file picture
and here is my second of my external file
$(document).ready(function() {
alert("hello");
});
I already tried putting the alert outside of the document ready function it still doesn't work.
I don't know why only the first one works please help. Also when I opened up my devtools and went to console it had a lot of but i can't put most of them because I don't have enough reputation to post more than one link. But here is one,
GET http://online-dnbard.rhcloud.com/tick/5620f410e59615263f000006 net::ERR_NAME_NOT_RESOLVED
ps. I am using brackets.
Note That you load up your external js file before jquery:
<script src="Javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
When you load up your file, you reffer to "$(document).ready", which isn't defined yet, so your browser throws an error.
Just change the order:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="Javascript.js"></script>
ps. Using the console in the future will save you a lot of time ;)

JQuery interferes with bokeh.js. Why?

TL;DR: my index.html declaration of jQuery with bokeh.js interferes with the ability for the script tags in the php page to manifest themselves into the div that they are supposed to be loaded into. Why?
I've been trying to embed the output of graph.create_html_snippet() from the python bokeh package. I was having so much trouble that I made a separate test html page just to post it to SO, when I discovered that my test page worked! Here it is:
<html>
<head>
<script src="js/bokeh.js"></script>
<script>
$(document).ready(function() {
$("#get_graph").click(function() {
$("#show_graph").load('hello.php');
});
});
</script>
</head>
<body>
<!-- click this to bring up graph -->
<div id="get_graph" style="width:100px;height:30px;background-color:#ddd;">Show graph</div>
<div id="show_graph"></div>
</body>
</html>
And hello.php is here:
<?php
echo 'hello';
?>
<script src="31b1ad52-e095-4ba1-89d0-69f0b898d677.embed.js" bokeh_plottype="embeddata" bokeh_modelid="31b1ad52-e095-4ba1-89d0-69f0b898d677" bokeh_modeltype="Plot" async="true"></script>
So now, confronted with the mystery of why it wouldn't work on my real page (not posted for brevity) and why it would work on my test page, I started subbing things in and out until I added this to the head of the my test page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
And then things stopped working. But then I realized, wait a minute, how did my original test page work in jQuery if I didn't give a script for jQuery in my <head>? I went back to my main page and deleted the JQuery script, and suddenly the embeddding worked okay. So I went into the bokeh.js script and found a bunch of calls to jQuery I don't quite understand.
Why is my declaration of jQuery interfering with bokeh.js? When I load the php page using a jQuery declared html page, the html element the php was loaded into will not have the script tags loaded into it, but all other php commands are okay. What's the deal? Since I solved the question while writing this, I guess my question is more out of curiosity/help for people who might run into the same thing, since embedding bokeh using php is one of the best applications for it.
Thanks for any help.
This is a recently discovered issue, you can track progress at:
https://github.com/ContinuumIO/bokeh/issues/554
There should be a point release that includes a fix for this very soon.

PHP include in head used for JS reference

This is a slightly weird question, but I couldn't find the answer anywhere and I'm far from a pro at PHP.
Basically, two things, firstly, can you use the PHP include function in the head of a webpage?
Also, if that is possible, is it also possible to use the included PHP file for referencing Javascript files? Because I've finished my template and I've been looking at different ways I can make quick changes to all pages once completed, and of course, PHP include seemed best, however, I may want to reference a JS file sometime, so would it be possible to have in the <head> something like this:
<?php include "ref.php"; ?>
And then that PHP file to look something like this:
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
And then, that should reference jQuery into all pages that have ref.php included in the head. Or am I just being silly?
If there's any other ways I could reference a JS file on all pages, please let me now :)
Yes that's fine. I think a term for the concept you're trying to go for could reasonably be "modularization". You can separate your site into different modules so that you only have to update the code in your include rather than changing the code for say, 10 different pages every time.
PHP simply processes all your code before it gets sent to the client, so the client (i.e. any web browser) will simply see the output.
Theoretically, you could even do something like this (even though there wouldn't be much use for it). This is simply to illustrate a point:
HTML:
<?php include "doctype.php"; ?>
<html>
<!-- etc. -->
doctype.php:
<!doctype html>
All the client would see is:
<!doctype html>
<html>
<!-- etc. -->
In my current site, I have the head in its own php file, my header (which contains navigation, etc.) in another php file, my footer in a php file, and then all my script elements inside yet another php file which is included at the end of the body.
There is a mistake i think in the syntax of include function , you may need to try this :
<?php include("ref.php"); ?>
By 'head of a web page' if you mean when beginning the code for a webpage, yes certainly you can do it. Infact it is more convenient to have repeating code blocks for all pages like the headers and footers stored as separate php files and then include them on pages. For eg <?php <!DOCTYPE html> <html><head><title></title><script...></script>......</head><body>..........?> in a file like head.php and <?php </body><footer>.......</footer> in a file like footer.php and them just use include on all pages
Yes you can do this but I would recommend that you take the time to break up the ref.php into header.php and footer.php so that head would be above the fold (body tag) and the footer will have the closed BODY and HTML tag so you can add any remaining items you need to in the footer.

Categories

Resources