Move JavaScript with php code to external file - javascript

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>

Related

Cannot pass variable from PHP to 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.

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

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>

Add div class with php in jQuery

My variable contains a color name. My example:
<?php
$myvar = blueColour;
?>
I need to add this value to body of a html page using jQuery:
<script type="text/javascript">
jQuery(body).addClass("<?php echo $myvar; ?>");
</script>
Can I use php inside jQuery this way? Thank you.
EDIT: its an wordpress site. I use this in a if to add that class on a specific page template.
<script type="text/javascript">
jQuery("body").css("color", "<?php echo $myvar; ?>");
</script>
yes, as long as your html file is interpreted by php (having .php/.phtml extension)
I did it. Worked.
Correct is:
jQuery('body').addClass("<?php echo $myvar; ?>");
with
jQuery('body')
not
jQuery(body)
if ( is_page_template('nameOfYouTemplate.php') ) {
echo '<body class='. $myvar .'>';
} else {
echo '<body>';
}

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