This question is not a duplicate of some of the other PHP & Javascript questions that have been asked here before, at least not one I have been able to find.
I have a .php file that contains some HTML elements that get rendered by the PHP for the sake of argument here we will say the file is located at http://url.php. It is looking for certain GET tags, and including a div if those get tags exist.
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV"></div>';
}?>
Of course I realize that this all happens on the server, and gets sent back to the clients web browser where the javascript takes over.
But in the javascript (on the same PHP page) I have the following code that executes on page load looking for that div tag and doing something with it:
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
While the page loads this should logically pop up the div if the URL is http://url.php?VAR correct?
However it does not. If I run the javascript code a second time in the console it works fine, so its not a misspelling (such as getElementsById or something silly like that).
How can this possibly render out of order like this? Should the PHP engine not render the HTML then pass it back to the browser before one line of JS is executed?
EDITED FOR CLARITY BASED ON COMMENTS BELOW:
<script type="text/javascript">
function doDIVStuff()
{
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
}
doDIVStuff();
</script>
<html>
<body>
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV"></div>';
}?>
</body>
</html>
use either window.onload() or document.onload(), see differences here
you could also place your script just before the end of your tag in the html although there could be unintended consequences in certain things in IE, seen here
Try to use jquery and document ready event:
$(document).ready(function(){
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
})
If you do not want to include jquery js lib, you can use the solution here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
Actually if you place the javascript code at the end of file after all php and html code it must work.I have tested it.
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV">Dilip</div>';
}?>
<script type="text/javascript">
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
</script>
but i think it is better to use onload event
window.onload=function(){if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}};
Or if you are ok to use jquery then its awesome..
$(document).ready(function(){
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
})
Any JavaScript that is not inside a function is executed sequentially as the page is interpreted. Your doDIVStuff(); call is executing before any HTML is interpreted on the page, therefore your "VARDIV" is not yet available in the DOM for the JS to read.
As others have suggested, the best approach is to listen for when the page is done loading and then trigger the call to your function.
Wrap in doc rdy() or just do something like this:
<html>
<head>
</head>
<body>
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV"></div>';
}?>
<script type="text/javascript">
function doDIVStuff()
{
if(document.getElementById("VARDIV")!==null)
{
console.log('div exists!');
}
}
doDIVStuff();
</script>
</body>
</html>
I'd say you should create a javascript file and put your code there so you can debug it.
Related
I've looked all around stack overflow for answers to this same problem. Usually it's simple syntax errors like omitting a closing tag or not writing the src attribute properly.
I could've sworn, though, that my html and js is correct, but I still can't get the jQuery working.
The normal javascript (function test()) works perfectly as it's linked with an html button using onclick. The $('#click') jQuery simply will not work, though.
<head>
<script type='text/javascript' src='jquery-3.2.1.min.js'></script>
<script type='text/javascript' src='test.js'></script>
</head>
<body>
<button type='button' style='margin: 1em;' id='click'>CLICK</button>
<button type='button' style='margin: 1em;' id='testButton' onclick='test()'>TEST LINKING</button>
</body>
Both js files and the html are in the same folder.
And here's the js.test:
$('#click').click(function () {
alert('jQuery Works!');
}); //NOT WORKING!
function test() {
alert('Okay!');
} //WORKING!
The problem isn't linking jQuery, it's about scope and DOM loading.
When you create a function globally it becomes a global reference that you can access whenever you want afterward.
When you call a function, or change the value of a variable, it needs a scope to know when to be called. It's generally the global scope but, when you use jQuery functions, you cannot know if your libraries are already loaded and therefore if you'll be able to access the functions they provide.
Therefore, wrap your EH in a document.ready function that is executed by jQuery itelf when the DOM is fully loaded. You can do it this way :
$(document).ready(function(){
$('#click').click(function () {
alert('jQuery Works!');
});
});
Or in a shorter way :
$(function(){
$('#click').click(function () {
alert('jQuery Works!');
});
});
Ahh, the problem here is that when you load the JS and jQuery file, browser starts going through you code, finds that it should now bind a click handler for #click, but when it actually goes to find #click on the page it doesn't get it. Because it has not been added to the dom yet !
You have three ways to deal with this :
Use the defer attribute of the script tag. It is used to define script that will not run until after the page has loaded
<script type='text/javascript' src='test.js' defer></script>
Just load your JS for the event handler after the divs like :
<head>
<script type='text/javascript' src='jquery-3.2.1.min.js'></script>
</head>
<body>
<button type='button' style='margin: 1em;' id='click'>CLICK</button>
<button type='button' style='margin: 1em;' id='testButton' onclick='test()'>TEST LINKING</button>
<script type='text/javascript' src='test.js'></script>
</body>
This is why you normally see the line
Place CSS includes in the head and JS include just before the close of the body tag
That's because without CSS your page would look ugly untill it has been loaded, and placing JS in the end would make sure that the DOM is in place for any action to be performed on it
You can use the $(document).ready(function(){ ... }) event handler. This event is triggered when the document is ready or essentially when the dom has been created. Binding you click handler here makes sure that the elem is actually available for your JS to bind to
You cant define a function in a way like this. you need to do this
$(document).ready(function() {
$('#click').click(function() {
alert('jQuery Works!');
//declare other function
});
});
`
I have a layout file where i included Jquery just before closing tag.
//layout.handlebars
<!DOCTYPE html>
<html>
<head></head>
<body>
{{{body}}} // renders the body content
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
I also have a page specific javascript(helper.js) that makes an Ajax call.
<div>Some sample data</div>
<script src="/js/helper.js"></script>
but the problem here is jquery is loaded at the end of the page but i am referring to it in the external javascript before jquery is loaded. which shows me '$' is not defined and i know that is obvious.
One solution to this will be like adding jquery to the head section but that is not what i want.
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Any help is much appreciated!!
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Yes, I assume you already understand the cause of the issue. As you see below the final content is ..
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>Some sample data</div>
<script src="/js/helper.js"></script> <!--Jquery is not loaded yet, and hence $ is undefined -->
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
As you already know one option is to move jquery anywhere in the HTML but make sure its loaded before any other jquery dependent files. Now since you don't want to take this option. we have another option.
Solution:
Our only aim is to make sure the jquery library is loaded prior to any other jquery dependent files.
We can get the files on document.ready using $.getScript()
$(function(){
$.getScript( "/js/helper.js", function( data, textStatus, jqxhr ) {
console.log( "Load was performed." );
});
});
Extras: If you feel this is a overhead and you cannot add this code to all the files in your page (since there can be too many files ), You can write a generic function and a global array variable , This function will check for file paths in the array and execute each one synchronously and remove from the array. Make sure this generic function is called in every document.ready event.
One Solution is that You can put the jquery script at the start of body tag before {{{body}}} section .. In this way your helper script will be rendered after jquery and your problem will be solved .....
Well its not pretty but you could use some kind of test and wait loop something like
<script>
(function test(){
if( window.jQuery ){
//your jQuery code
} else {
setTimeout(function(){ test(); }, 200);
}
})
</script>
First, I build a single php page with
<script type="text/javascript" >
function ShowDIV()
{
if (popUpDiv.style.display=="none")
{popUpDiv.style.display="block"; blanket.style.display="block"; }
else
{ popUpDiv.style.display="none"; blanket.style.display="none";}
}
</script>
and in my code I can call this function
<a href="#" onClick="ShowDIV();">
everything works...
but then I wanted to separate that file into
main.php (which now includes header.php)
in my header.php, I added the same JS code:
<script type="text/javascript" >
function ShowDIV()
{
if (popUpDiv.style.display=="none")
{popUpDiv.style.display="block"; blanket.style.display="block"; }
else
{ popUpDiv.style.display="none"; blanket.style.display="none";}
}
</script>
but now it doesn't work, my console tells me:
Cannot read property display of Undefined
Does it mean I have to pass somehow the propreties to the new header.php file?
There should be Selector for blanket so that you can access its properties, please check your code for blanket, right now what happening there is no blanket selector that`s why its undefined.
so please check selector is exist then only you can access its properties.
EDIT
you should never have two elements on the same page with the same ID.
As my website has only one page, and the index.html was getting really long and impossible to read. So I decided to put each section in a different HTML file and use jQuery to included it.
I used jQuery's include in the way as it has been mentioned here to include a external HTML file but apparently it doesn't work for my website. I really don't know what is the problem.
Here is the link of my workspace.
Here is what I am doing in index.html file to include other sections
<script src="./js/jquery-1.11.1.min"></script>
<script>
$(function() {
$("#includedContent").load("./page1.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page2.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page3.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page4.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page5.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page6.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page7.html");
});
</script>
I also used this method to make sure the file is accessible and everything was fine. So the problem is not the accessibility of the files
You are overwriting the contents of #includedContent seven times (see documentation of jQuery.load). With AJAX, there is no guarantee which request will complete first so you will end up with random page content inside the container.
The solution is to create containers for each page and load each page inside its dedicated container, something like this:
<div id="includedContent">
<div class="page1"></div>
<div class="page2"></div>
<div class="page3"></div>
</div>
$(document).ready(function() {
$("#includedContent .page1").load("page1.html");
$("#includedContent .page2").load("page2.html");
$("#includedContent .page3").load("page3.html");
});
NB: Having said all that, I do not understand how AJAX solves the problem of the page being too long/impossible to read.
There are several things that look odd to me:
all your load functions run at document ready, which is weird while having all the same target. load replaces (not adds) the content of the selected element with what is being loaded, you probably are trying to add all the html contents, but your current setup would actually just load page7.html into #includedContent
the paths look strange to me, i guess ./ may cause errors, try to leave out ./ everywhere.
rather than loading an entire html page, you might just want to load a piece of that file (i dont know how pageX.html looks), for example you would not want to load the <html> node entirely, rather the content only: .load('page1.html #content')
are you including jquery correctly? there is no .js in your inclusion
I want to clear my code a little bit and I want to run my jquery code without any function call in the html file. My actual code is :
HTML:
<head>
<script src="js/colorpick.js"></script>
<script>
$(document).ready(function() {
colorpick_start();
});
</script>
</head>
JS:
function colorpick_start() {
...
}
But if I write for example an alert in the first row of the js without any function call, that works.
alert('test');
function colorpick_start() {
...
}
But this is not working for jquery selectors or something. Is there any solution to get my jquery working without code in the html file?
I want my html file to look like this, if this is possible:
<head>
<script src="js/colorpick.js"></script>
</head>
The
$(document).ready(function() {
Waits until the DOM is ready for selectors etc.
If you add the
$(document).ready(function() {
to your colorpick.js file it will wait for the DOM to be ready and then execute colorpick_start().
And believe me this catches out most people when they start using JQuery.
In order to achieve this:
<head>
<script src="js/colorpick.js"></script>
</head>
Move the document ready call to the js file you are referencing in your HTML file and make sure that the method called is present.
$(document).ready(function() {
colorpick_start();
});
This should so it.
Put your script
<script src="js/colorpick.js"></script>
before </body> tag. This will ensure that your page is loaded fully before script starts.
$(document).ready(function() {
colorpick_start();
});
this code is working because you are calling your function after document is loaded. document load is event. you can put your function on any event you want, but it wont start if you just define your function. You have to somehow call your function. example would be on click (or on document load)
<div id="example"></div>
$("#example").on('click', function () {
your function here
});
Use that code:
$(function(){
$('.colorpicker').val("colorpicker"); //or whatever you like
});
Plnkr example code