Cannot pass variable from PHP to JavaScript - javascript

I have this simple script
<!DOCTYPE html>
<html>
<head>
<?php
$latitude = 53.071174;
$longitude = 28.296536;
?>
</head>
<body>
<script>
var jsLatitude = <?php echo json_encode($latitude); ?>;
var jsLongitude = <?php echo json_encode($longitude); ?>;
alert(jsLatitude);
alert(jsLongitude);
</script>
</body>
</html>
but it gives me a Syntax error at this line
var jsLatitude = <?php echo json_encode($latitude); ?>;
What am I doing wrong?

Ok, as suggested by #Markus Zeller and #Teemu it was just the extension of the file (I was working on an HTML file instead of a PHP) and I was working on my personal PC.
Changing the extension and uploading the script to a server with PHP installed solded the problem.

Related

Move JavaScript with php code to external file

I wrote my script directly in my html file and works fine. I want to move my script to external file, of course I know how to move it to external file for example js/myscript.js then add it in my html but I am also using php
and there is a problem because it isn't working when it's in external file.
I am using php in my JS like:
user_name = "<?php echo $_SESSION['name'] ?>";
$scope.username = user_name;
and this is where I am starting session
<?php session_start();
if(!isset($_SESSION[ 'username'])) {
header( "Location: login/login.php");
}
?>
<!DOCTYPE html>
How can I use it in external file? is it possible?
May use a JS variable in main html page for user_name and this variable can be used in external JS
<?php session_start();
if(!isset($_SESSION[ 'username'])) {
header( "Location: login/login.php");
}
?>
<!DOCTYPE html>
<head>
<script>
var user_name = "<?php echo $_SESSION['name'] ?>";
</script>
<script src="js/yourexternal.js"></script>
</head>
in yourexternal.js
$scope.username = user_name;
Yes it is possible. I am using MVC framework on php.
I have a file called view_fncs.php which contains functions for header, navigation and footer e.g:
function showHeader($title="My Title")
{
echo '<!DOCTYPE HTML>';
echo '<html lang="en">';
echo '<head>';
echo '<title>' .$title. '</title>';
echo '<meta http-equiv="content-type" content="text/html;charset=utf-8" />';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<script src="js/javascript.js" type="text/javascript"></script>';
echo '</head>';
echo '<body>';
}
As you can see it has a link to the JS file.
In my view.php file I do something like this:
<?php
include ("view_fncs.php");
showHeader("Add a new submission");
?>
The same principal applies to other script. Just link the two files with include and then specify the function.
You could set var $userName in the .php file. this way the variable $userName is assessable in the js file.
In php file:
<script>
var $userName = <?php> echo $_SESSION['name'] ?>
</script>
<script src="js/someJs.js"></script>

Executing php file from another php file

Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help

Passing PHP Array to Javascript OnLoad

I am currently trying to pass in PHP array to a javascript Function through onload();
In my SimilarDomains.php:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
I do this to pass it as a string object in order to later process the string using JSON.parse(). In the javascript i have
var obj = JSON.parse(domainsJS);
for string processing. But it seems like I have a SyntaxError: syntax error # line 1. This is the HTML Doctype. If I remove the doctype, it just goes to the next first line. it only appears when I have the body onload calling php as I did.
How can I process this php array in order to be used in JavaScript. After all this is said and done, I then have to input the processed values into a JS array.
Here is what the body onload turns out to be in the HTML
<body onload="init("{"0":"estatelawyer.com","1":"reaestatelawyer.com","2":"estately.com","3":"thestate.com","4":"estaterescue.com","5":"boisestate.edu","10":"99acres.com","11":"1point3acres.com","14":"green-acres.com","22":"backcountry.com","24":"baby-kingdom.com","25":"landattorney.com","27":"siteground.com","28":"247realmedia.com","30":"siteground.biz","31":"arealme.com","32":"farming-simulator.com","33":"amkingdom.com","34":"searchengineland.com","35":"shoretelsky.com","36":"grantland.com","38":"amsoil.com","40":"lostrealm.ca","41":"kingdomofloathing.com","42":"shorewest.com","44":"domaintools.com","45":"domain.com.au","46":"realmadridstream.net","47":"farming2015mods.com","48":"travelandleisure.com","49":"landofnod.com","51":"bringmesports.com","52":"cricketcountry.com","53":"bringthebaconhome.com\/user\/dashboard","54":"ollando.com","55":"domain.com","57":"travelandlearntrips.com","58":"scarffruit.country","59":"78land.com","92":"propertylawyer.com","93":"propertylawyergroup.com","94":"propertyattorney.com","95":"rocketlawyer.com"}");">
You should just need to echo it straight up without any extra quotes because it's a JSON object
<body onload="init(<?php echo $domainsJS ?>);">
Add the json to a var in the JS
echo <<<EOT
<script type="text/javascript">//<![CDATA[
var jsn = " . json_encode($similarDomainsUnique);
var obj = JSON.parse(domainsJS);
//]]>
</script>
EOT;
This is poor coding:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
There is no reason to be jumping back and forth from PHP mode to HTML mode.
There is PHP overhead to each time you change modes.
Below is the basic proper way to create an HTML page.
I like to get the HTML on its way to the Browser ASAP. That is why I flush the output buffer somewhere just after the <body> tag and the Browser will have a few things to do preparing for Start Render.
To accomplish your passing json to <javascript> I assign the value to $js then embed $js in the `
And PHP is never switched to HTML mode.
<?php ob_start("ob_gzhandler");
header('Content-Type: text/html; charset=utf-8');
header('Connection: Keep-Alive');
header('Keep-Alive: timeout=50, max=100');
header('Cache-Control: max-age=3600');
echo <<<EOT
<!DOCTYPE html>
<html lang="en">
<head><title>Sample</title>
<style>
body{font:400 1emArial,sans-serif;color: #f00 ;}
#page{width:100%;background:#ff0;border:solid .5em #000;padding:2em;}
#contents{max-width:50em;background:#00f;margin:0 auto 0;height:10em;color:#ff0;padding:1em;}
h1{color:#000;text-align:center;}
</style></head><body><div id="page">
EOT;
ob_flush();
$js = "\nvar jsn = '" . json_encode($similarDomainsUnique) . "';\n" ;
echo <<<EOT
<h1>Headline</h1>
<p>Paragraph</p>
</div></div></body>
</html>
<script type="text/javascript">//<![CDATA[
function init(){
$js
var obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>
If you need obj to be use by other functions:
<script type="text/javascript">//<![CDATA[
var obj = '';
function init(){
$js
obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>

php in external javascript file

I have a the code below in my js which obviously works if the js is in the php file
filter: '<?php echo $my_cat>'
how can i make a variable maybe in the php file and pull it in my external js file?
You have to place this below code at the top part of your test.php page
<script>
var filter = '<?php echo $my_cat>';
</script>
and simply you can check it on your external.js file by alert
alert(filter);
<?php
function showme(){
echo "HelloWorld";
}
?>
<script type="text/javascript">
var my_var = '<?php echo showme(); ?>' ;
</script>
You can also use short tags.
<script>
var filter = '<?=$my_cat?>';
</script>

Using Javascript to access PHP variables

How can I access PHP variables from Javascript where the PHP code exists in a separate file?
The code I have is:
<?php
$res = "OK";
?>
<html>
<head>
<script type="text/javascript">
function myFunc()
{
res = <?php echo json_encode($res); ?>;
console.log("res = " + res);
}
</script>
</head>
<body>
<button onclick="myFunc()">Click</button>
</body>
</html>
Now, if I were to move my php code to a separate file called a.php, how can I access $res? Assume I am calling a.php with a GET request (XMLHttpRequest object).
Try-
res = "<?php echo json_encode($res); ?>";

Categories

Resources