0

Let's say i have a variable in a php-file (index.php):

$PHP_variable = "string";

And i want to pass it to my JS file (functions.js) that's currently being read within the php-file. Is that possible?

For example, i have this in my php-file:

 <input type="text" name="textfield" value="'.$PHP_variable.'" />
 <input type="button" id="actionButton" />

And in the js-file:

$('#actionButton').click(function(){
 alert(THE_PHP_VARIABLE);
});

How is it possible to pass $PHP_variable to the js file? I'd prefer not to use the js code directly on the php-script (i know how to solve it that way).

user2994294
  • 81
  • 1
  • 14

3 Answers3

0

It sounds like you're thinking of using PHP to generate Javascript, which is possible although it's a bit odd. It's also curious that you really aren't passing the variable, you're using it to render a javascript variable of the same value.

Instead, I think what you'd really want to do is use JS to read the variable from the HTML element's value attribute, since you're already storing the variable's value there.

This can be done a lot of ways, but since it looks like you're using jQuery it'd just be:

$('#actionButton').click(function(){
  $value = $this.attr('value');
  alert($value);
});
STW
  • 44,917
  • 17
  • 105
  • 161
0

You were almost there -

$('#actionButton').click(function(){
    var THE_PHP_VARIABLE = $('input[name="textfield"]').val();
    alert(THE_PHP_VARIABLE);
});

Since the value is echo'd out when the page loads you can get that quite easily by using val() on the correct element.

If you want to assigned variables at the time the page is loaded you could also do this in your PHP -

<script type="text/javascript">
<?php
   echo "var THE_PHP_VARIABLE = " . $PHP_variable .";";
?>
</script>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
0

Thanks for all the answers, i chose to use a hidden input field with an id and the php-variable as the value for this input, then in the js-file i simply get the val() from this hidden input

$input_val = $('#hiddenInputID').val();
user2994294
  • 81
  • 1
  • 14