Skip to content Skip to sidebar Skip to footer

Passing A PHP Variable To JavaScript

I am having problems passing any kind of variable from PHP to JavaScript. Here is a simple example at jsFiddle. Why does it not return my string? http://jsfiddle.net/funinabox/VkNe

Solution 1:

You are missing "

var testvar = "<?php echo $teststring; ?>";

Here is a full example

<?php
//create php test string    
$teststring = "mystring"; 
?>


<html>
   <head>
   <script>
   //Convert Php string to JavaScript string
    var testvar = "<?php echo $teststring; ?>" ;
    //Display output of the array elements;
    alert(testvar);
    </script>
    </head>
<body></body>
</html>

Solution 2:

I reinstalled xampp and then made 1 change in c:\xampp\apache\conf\httpd.conf in the mime section section by adding (I did it in line 402 but anywhere in that section should be ok)... AddType application/x-httpd-php .html .htm

NOW IT WORKS!!!!!!!! This looks like a big mistake in the current xampp distribution for Win 7 32-bit.


Solution 3:

try to do link below:

<?php
//create php test string    
$teststring = "mystring"; 
?>


//Convert Php string to JavaScript string
var testvar = '<?php echo $teststring; ?>' ;
//Display output of the array elements;
alert(testvar);

Solution 4:

My environment uses templates so this is not copy and paste code. However I was able to pass the variable to Javascript by doing this:

$teststring = 'mystring'; 

 $page_headers = <<<PAGEHEADERS
 <script>
    window.onload=function(){   
        var testvar = '$teststring';
        alert(testvar);
    };
</script>
PAGEHEADERS;

As long as the php variable is defined first you should be able to get a value from it simply by calling it.


Post a Comment for "Passing A PHP Variable To JavaScript"