0

hello,
I am S L O W L Y working through learning/writing a JS project.
here is the core issue.:

var pt =<? echo json_encode($prt);?>
alert(pt) // for diagnostic purposes

json is flattening the PHP array to be used in the script.
However, the alert shows me that I only get {[ ,which is just before the first set of double quotes.
JS quits at the double quotes, leaving me with an undefined array.

How do I fix this?

Edited by JRM: code is incorrect

3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by ShawnCplus
1

What's the string outputted by your echo statement? Can you look at the page source and paste the exact output your see in view source? Also, this might help.

0

What's the string outputted by your echo statement? Can you look at the page source and paste the exact output your see in view source? Also, this might help.

Thanks for the reply.
I the mean time I have figured it out.
It seem that JS is rather picky about PHP calls in it's scope.
By moving the jason_encode call out into the form body, and then echoing the resultant string got it working:

<?PHP 
//this is now in the form 
$string = json_encode($prt);
?>

the JS code is now as follows:

pt =<? echo $string; ?>

The code is essentially the same, this version works, the version in the previous post did not.
I guess JS does not allow PHP function calls from within?

0

JS has absolutely no clue that PHP is even being called since the PHP code is evaluated before the page gets to the user and the Javascript isn't evaluated until _after_ the page gets to the user so there is a different issue

0

JS has absolutely no clue that PHP is even being called since the PHP code is evaluated before the page gets to the user and the Javascript isn't evaluated until _after_ the page gets to the user so there is a different issue

OK, that all makes perfect sense.
However, if the PHP code is meant to be echoed and stored into a JS variable, where is the PHP value stored until the onload JS function executes?

0

OK, that all makes perfect sense.
However, if the PHP code is meant to be echoed and stored into a JS variable, where is the PHP value stored until the onload JS function executes?

It's not stored anywhere, it will always exist in the JS as far as the browser knows.

Example (Both of these are exactly the same as far as the browser is concerned):

<?php $somestring = "Hello"; ?>
<script type="text/javascript">
alert("<?php echo $somestring; ?>");
</script>

When the above hits the user they get this: (Go ahead, view the source of the page, you will see this. You'll never see PHP in the source of the page since it's not the client (browser) that's executing the PHP code)

<script type="text/javascript">
alert("Hello");
</script>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.