I am stuck with this issue. I have a js function into a scripts.js file:
var userLoggedIn;
function openPage(url) {
if(url.indexOf("?") == -1) {
url = url + "?";
}
var encodedUrl = encodeURI(url + "&userLoggedIn=" + userLoggedIn);
$('#mainContent').load(encodedUrl);
}
I call the javascript function from a php file like this:
<?php
//This file should check if the requested url is sended by AJAX or it's manaually typed by the user into the browser
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
include 'includes/config.php';
include 'classes/Artist.php';
include 'classes/Album.php';
include 'classes/Song.php';
} else {
include 'includes/header.php';
include 'includes/footer.php';
$url = $_SERVER['REQUEST_URI'];
echo "<script>openPage('$url')</script>";
exit();
}
?>
It works fine when it’s called from an onclick event into the HTML document, but it doesn’t works when I enter manually the url. It prints a string into the screen. However this code is taken from some sample coding pages and it seems to work this way. What am I missing here?
Thanks in advance for the help and be patient… i’m a beginner on this!!
2
Answers
So, after reviewing all the code i found the problem. There was a missing ">" in the html closing tab. Now it works!! Thank you for your help!
First of all you need to have the mentioned above js code loaded somewhere. Do you have it loaded in header or footer? (Directly or by loading your
scripts.js
?)Be sure to have:
Somewhere printed in your code. Do you have it in your footer or header?
Assuming that you have your js code in scripts.js now you can execute after page loads, but be sure print the
<script>
part WITHIN your<html>...</html>
. So if you print out</html>
in yourfooter.php
then be sure to print:BEFORE loading of footer (but after loading of
scripts.js
);While you learn a bit more you will get to know that actually it is a bad thing to execute code parts like that: you should separate your markup from code which executes things directly from it.
Modern frameworks will assist you with that, there is also
defer
attribute of the script element (https://www.w3schools.com/tags/att_script_defer.asp) which helps to execute the code after the page actually loads.