Copy php variable to a JavaScript variable cause Design issue - javascript

**This is my code **
I am sending copying data from a php variable to a JavaScript variable here
<?php
include('includes/config.php');
include('includes/classes/Artist.php');
include('includes/classes/Album.php');
include('includes/classes/Song.php');
if(isset($_SESSION['userLoggedIn'])){
$userLoggedIn = $_SESSION['userLoggedIn'];
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
// echo "<script>console.log('$userLoggedIn')</script>";
}else{
header('location:register.php');
And if i use the echo statement in the if statement here
it cause this. see the left side navigation bar;
Error image
And if i don;t use the echo statement the page is fine looks like this
Without error

I can't access the picture you uploaded right now, but I saw an error
echo "<script> var userLoggedIn = '" . $userLoggedIn . "'; alert(userLoggedIn); </script>";
Change the part we print on the screen in this way, data will be displayed on the screen.

I used this code inside the body of the html part and it works fine
<?php
if($userLoggedIn){
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
}
?>

Related

PHP Pass Variable to new Window.Open Javascript

I have read the following posts, but they are a little over the top for me. I think I'm trying to do something fairly simple, and would like some guidance.
How to pass variables and data from PHP to JavaScript?
passing PHP variables across javascript windows.open to another PHP page
Posting a php variable to a new window
Here is the case:
I have a php script which is very simple, it calls another script and passes 2 variables:
<?php
echo '<script type="text/javascript" language="javascript">
window.open("http://callpage.com/utils/cdr.php?callernum=123456789&calltime=2017-02-22 16:24:12");
</script>';
?>
Note: This is just a "hardcoded" example.
The next script, takes those numbers and builds file/url variable.
Lets say
$file = /var/www/html/file.wav
What I'm trying to do open a new window to the effect of :
http://newpage.com/$file
I have read and found that I think the best use is Javascript, but I can't seem to get my variable into the Javascript.
Here is what I would like to get working:
<?php
$file = /var/www/html/file.wav
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/$file");
</script>';
?>
A few notes:
I don't want to "redirect" the old page, I want it to stay open, and the remote page isn't on the same domain
(one is a.domain.com and the other is b.domain.com).
I don't care about window sizes, etc, its a wav file that I'm expecting the browser to just play with a simple Browser default interface for Wav.
if I understood correctly what you want, you have to concatenate the string with the variable in order to be replaceed
<?php
$file = '/var/www/html/file.wav';
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/'.$file.'");
</script>';
?>
Use string interpolation with double quotes for the echo statement and single quotes everywhere inside the javascript:
echo "<script type='text/javascript' language='javascript'>
window.open('http://newpage.com/$file');
</script>";
The interpolated PHP variable $file should be correctly interpreted as a string and the value it holds should be displayed in the URI of your javascript.
Check out this easy to understand info about variable interpolation http://phppot.com/php/variable-interpolation-in-php/
Here is my "final" code snippet:
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$uid = $row['uniqueid'];
foreach(glob($path. "*". $uid. "*") as $file) {
$link = "http://newpage.com$file";
echo "<script type='text/javascript' language='javascript'>
window.open('$link');
</script>";
}
}

how to create a dynamic redirect link with js and php?

PHP has no relation and behavior with browsers and in some times it makes some mistake. For example we can't set for header function to redirect to a page in a blank page. Because it has no relation with the browsers and for doing this, we should use JS .Now I'm mixing these two languages to reaching the goal.
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo '<script>window.open("Location: <?php $search;?>");</script>';
?>
The goal is this code but it doesn't work. I want get a string from a first page then post it with post method and then past it to a static address for redirecting with blank target. Thanks.
I think you are trying to open a new url when the page is loaded.
So if you trying to do this check the code below.
This way you are mixing the parameters received from client, processing them and them sending back to the client.
Then you use the javascript with the window.onload function to execute the redirect page when the page is loaded with the received parameter.
<?php
$word = "1";
$tag = "www.yahoo.com/" . $word;
echo '<script text="text/javascript">window.onload = function(){window.open("'.$tag.'");} </script>';
?>
Not sure I fully understood your question, but have you tried something like this:
<?php header("Location: $search");
If you are "changing" the web page. Do not use window.open
Use window.location = 'http://www.google.com/';
in your example do this
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo "<script>window.location = '$tag';</script>";
?>
(copy the code above, and it should work perfectly for what you're asking for)
I fount the way.
thanks all.
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo "<script>window.open( '$tag' );</script>";
?>

Concatenate php variables and symbol to javascript function in php echo

I finally got the php variables to pass to the javascript function but they are passing as multiple and getting a warning.
Use of undefined constant app_name - assumed 'app_name'
How can i define the variables?
echo('<li> <a href="#" onClick="runthis(\''.str_replace("'", "\\'", $row[activity]).'\',\''.str_replace("'", "\\'", $row[app_name]).'\');">');
Javascript
function runthis(activity) {
alert(activity);
//$('#live-area').load('../assets/php/multibox.php?id=' + activity);
}
I am trying to concat $row[activity] and $row[app_name] with /
my php explodes on / and breaks into variables
UPDATE
Here is what im doing with the data.
if (isset($_GET['id'])) {
$app = $_GET['id'];
$array2 = explode('/', $app);
$activity = $array2[0];
$app_name = $array2[1];
$SQL1 .= "WHERE activity = '$activity' ";
}
I don't think im handling the string properly.
What should this look like?
I updated the echo onClick to this
echo ('<li> <a href="#" onClick="runthis(\'' . $row['activity'] . '/' . $row['app_name'] . '\')">');
It passes correctly to javascript but when $_GET loads it i get no results
You're dumping PHP output into Javascript context. Use json_encode() to do this properly:
echo '<li>..... ', json_encode($row['activity']), '</li>';
As it stands right now, your array keys aren't quoted, which'll probably cause PHP to issue various warnings, and those warnings will get output in your JS code, causing syntax errors.
json_encode() will take care of ALL the necessary quoting/escaping for you. It'll also be far more readable/maintainable than the abomination you've come up with.
comment followup, split onto 3 lines for a bit more legibility:
echo '<li> <a href="#" onClick="runthis(';
echo json_encode("{$row['activity']}/{$row['app_name']}");
echo ')">';
You're getting Use of undefined constant app_name - assumed 'app_name' because you're saying $row[app_name] instead of $row['app_name'].

php echo of javascript with php echo inside

I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.

Pass php variable via js/jquery redirect url function

In my php i'd like to redirect via javascript/jquery a url with a php variable via js function.
My js function
function Redirect(url){
document.location.href=url;
}
In my php page i try in this way but I fear there is a problem with the syntax in the $url.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
If I try to redirect in this way everything works perfectly (no Redirect function).
echo "<script>
document.location.href='index.php?opz=OK#PG2&id=$_GET[id]'
</script>";
Can anyone suggest me what is the correct syntax to pass my php variable via the js Redirect function? Thanks.
Just change echo "$(function(){ Redirect($url); });"; to
echo "$(function(){ Redirect('$url'); });";
Notice the quotes. the url is to be passed to the Redirect function as a string. So enclose it in single quotes. like Redirect('$url');
your problem is simple:
echo "$(function(){ Redirect($url); });";
should be replaced with
echo "$(function(){ Redirect('$url'); });";
Why you are trying to redirect your webpage using javascript.
You can do it with PHP also. Use PHP header() function to redirect your page.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
header("Location:".$url);
}
Assuming the Javascript code being generated is OK try window.location
try like below
if ($opz = 1){
$param = 'opz='.urlencode("OK#PG2").'&id='.$_GET['id'];
$url = "index.php?".$param;
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
and pick up opz using urldecode();
The problem is caused by the fact that your generated HTML looks like this:
Redirect(index.php?opz=.....);
As you can see, you're missing quotes.
To put a variable from PHP into JavaScript, I always use json_encode. This ensures that, no matter what I pass it, JavaScript will see the same thing. It takes care of quoting, escaping, even iterating over arrays and objects.

Categories