0

I have a variable set in the PHP with some relevant information that I need to process with the Javascript, but I can't figure out how to port that information over to the Javascript.

I first create a test variable in one javascript file, x Test='<--!TestString-->' In the PHP I use str_replace to alter the value of the variable with the relevant data

str_replace('<--!TestString-->',seralize($data), x)

Now I try to see if the data has been added in a different file using alert(Test)

and it shows me <--!TestString-->

Is there a better way to do this and have the data show with the alert function so I can start processing it?

chris85
  • 23,846
  • 7
  • 34
  • 51
Jim
  • 101
  • 3
  • 9
  • JS is client side, PHP is server side. Is the `str_replace('<--!TestString-->',seralize($data), x)` being executed via AJAX? – chris85 Jun 22 '16 at 20:50

4 Answers4

1

I don't understand your approach at all.

Of course the ideal way to accomplish is to use AJAX to grab data from the server and get into the client side so you can work with it in Javascript. (You can Google "Ajax php and javascript")

The easiest way to accomplish this is to just print the variable in PHP but in a context that it will be available to JS in the client.

<html>

<body>

  <script>
    var x = <?php echo json_encode($phpvar); ?>;
    console.log(x);
  </script>

</body>

</html>

I won't argue with anyone that disapproves of that approach but its easy and it works.

Dan
  • 10,614
  • 5
  • 24
  • 35
0

Use <script> tag?

<script> my_value = 'some'; </script>

Use AJAX?

// with jQuery:
$.get('/data.php',function(data){/*...*/})
Dimava
  • 7,654
  • 1
  • 9
  • 24
0

PHP is executed on your server, Javascript in the client (ie. Browser of the user visiting your website). So PHP can not change variables of your JS code once the page has been sent to the browser. But what you can do is set the variable in PHP and insert it in your JS code like this:

<?php
    $test="some important info here";
?>

<script>
    alert("<?php echo $test ?>");
</script>

If you need to change the variable by the server, you would need to use AJAX to load the new value.

Armin Hierstetter
  • 1,078
  • 2
  • 12
  • 27
0

As mentioned before we might not be understanding your approach to your problem.

PHP is executed on the server side while Javascript in the client. PHP cannot change variables of your Javascript code once the page has been sent to the browser. What must be done is to invoke PHP by using preferably AJAX with jQuery.

Look into AJAX PHP with JSON. Perhaps you are looking into the json_encode(value) function?