Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

set value of input with php variable

Im trying to do something really simple I know I should probably be using ajax but I’m just doing some quick tests.

so I have a display.php file with some variable and I want to display the PHP variable in the input text by using document.getElementbyID.value = myVariable

//PHP
<?php
$name = 'Patrick';
?>

//HTML
First Name: <input type="text" id = "fname" name="fname" value=""   >

//JS
<script type="text/javascript">
     var f = <?php echo($name); ?>;
    document.getElementById("fname").value = f;`
</script>

I keep getting the error Uncaught ReferenceError: Patrick is not defined
Not really sure whats wrong with my code it looks pretty simple but it don’t want to put the value "Patrick" in the input box.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tried different ways of writing it with ” or using json_encode but didnt change anything still getting same error.

>Solution :

Uncaught ReferenceError: Patrick is not defined

That’s because the resulting javascript is:

var f = Patrick;

Which means set f to the contents of the variable Patrick.

Since there is no variable defined that is named Patrick you’ll get the uncaught reference error.

You need to put Patrick in quotes like so:

var f = "Patrick"; // <-- Note the "

Note, since you want to pass data from PHP to JavaScript, a better way would be to use JSON like this:

var f = <?php echo json_encode((string)$data); ?>;

This allows you to pass more complex types of data¹ AND you’ll get proper escaped strings.

Proper escaped strings? If the user input is Test " (note the double quote) a primitive approach will break because the resulting javascript will be:

var f = "Test "";

This is not only a bug, but a security issue since user input could contain arbitrary javascript that would get executed.

¹ just remove the (string) cast.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading