Link to home
Start Free TrialLog in
Avatar of DMTrump
DMTrumpFlag for United States of America

asked on

How do I put a PHP variable into a javascript function?

Here is a drastically stripped down code stub:
<!--  ************************************** -->
<!doctype html>
<html lang="us">
<?
$thecounty = $_REQUEST['county'];
require ("getcities.php");
?>
<head>
	<link href="css/smoothness/jquery-ui-1.10.4.custom.css" rel="stylesheet">
	<script src="js/jquery-1.10.2.js"></script>
	<script src="js/jquery-ui-1.10.4.custom.js"></script>
</head>

<body>
<?
   $thecities= cities("$thecounty"); 
   echo $thecities;   // just to show that the string of cities is really returned by the cities function
?>

<br>
<form>
<input id="autocities" size=20 name="icity" />
<input type="submit" value="submit" id="submitForm" >
</form>

</body>
<script>
$(function() {
		
var citiesincounty = [
"thecities", "php", "variable", "needs", "to", "go", "here"
];

$( "#autocities" ).autocomplete({
                    source: citiesincounty
}); 
});
</script>
</html>
<!--  ************************************** -->

Open in new window

What I need to do is take the variable $thecities returned by the php function "cities" and place it into the javascript variable "citiesincounty".  I have confirmed that $thecities is correctly formed for the Javascript array (if I paste it in in place of the fake array, it works.

Please provide your answer by editing my code.  Thanks!
Avatar of Gary
Gary
Flag of Ireland image

If I am following you correctly

var citiesincounty = <?=json_encode($thecities)?>;

Open in new window

Amendment to that after rereading the code.

...
$thecities= cities("$thecounty"); 
// Assuming a comma delimited list
$thecities=explode(",",$thecities);
...

...
<script>
$(function() {
var citiesincounty = <?=json_encode($thecities)?>; 
...

Open in new window


Can you confirm what $thecities is - is it an array or string...?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

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
SOLUTION
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
Avatar of DMTrump

ASKER

thanks all for helping out - I think I've got to be more careful about checking for typos in my code before I decide that something won't work the way I expect.