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

$name = 'Patrick';

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

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

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.

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.

Leave a Reply