Link to home
Start Free TrialLog in
Avatar of Nika Gudge
Nika GudgeFlag for United States of America

asked on

how to assign a php variable to html input text box

document.getElementById("resp_first_name").value = <?=$firstNm ?>; <--- "Amy"
                document.getElementById("resp_last_name").value = <?php echo $lastNm ?>;


error:  Amy is not defined
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

We might need to see a little more.  But first let's try this:

var_dump($firstNm);

If that shows an undefined variable, then you want to look back into the code to see where $firstNm would be created.  And please note that PHP variables are case-sensitive
Avatar of Chris Stanyon
Your value should have quotes around it and I wouldn't advise using shorttags. It'll break your site if your hosting provider ever turns them off.

document.getElementById("resp_first_name").value = "<?php echo $firstNm ?>";

Open in new window

@Chris: It is subtle, but see the note here:
http://php.net/manual/en/language.basic-syntax.phpmode.php

The short open tag is like this: <? $x = 3; ?>
The short echo tag is like this: <?=$x; ?>

Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting (which should always be off).
Thanks Ray,

I always used to use <?= as a shortcut to echo, and I updated my version of PHP and it broke, as the echo shortcut was directly tied to short_open_tags. Now in PHP 5.4 they've changed it so that short_open_tags is separate to the short echo tag.

I learned my lesson and it didn't take me long to get into the habit of full open tags and echo - particularly with Aptana shortcuts, and code completion - php TAB e TAB :)

<?php echo... will always work
<?= ... may or may not work depending on version and config

Better safe than sorry. Now I always use the long version :)
Yep, I'm with you there. It simplifies using XML, too.
ASKER CERTIFIED SOLUTION
Avatar of rinfo
rinfo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial