Question

I have a php array as below : $city_more = $form->select("GalStore.gal_location_id", $gal_locations,null,$city_attributes);

which produces var_dump($city_more):

string '<select name="data[GalStore][gal_location_id]" id="locations_list">
<option value="">--- Select City ---</option>
<option value="11">Ahmedabad</option>
<option value="31">Aijwal</option>
<option value="3">Bangalore</option>
<option value="26">Bhopal</option>
<option value="9">Bhubaneswar</option>
<option value="30">Bidar</option>
<option value="10">Chandigarh</option>
<option value="4">Chennai</option>
<option value="1">Delhi - NCR</option>
<option value="34">Dhaka</option>
<option value="21">Dimapur</optio'... (length=1426)

I want to use this array in a javascript function :

$('#add_more_city').click(function(){
   var city = '';
   alert(<?php echo $city_more; ?>);            
});

But its not alerting anything ! Is my process is wrong ?

Was it helpful?

Solution 2

Question

What do you want?

  • Pass the php array for javascript to do what?
  • Pass the php array to javascript in JSON format?

Possible Solutions

<script type="text/javascript">
$(document).ready(function() {
  // alert in JSON format
  alert("<?php echo json_encode($city_more) ?>");
  });  
</script>

<script type="text/javascript">
$(document).ready(function() {
  // alert in "php" format
  alert("<?php echo $city_more ?>");
  });  
</script>

OTHER TIPS

You are missing the quotes in your alert() call. You calling like this:

alert(test);

When it should be:

alert('test');

Replace your alert() call with

alert('<?= $city_more; ?>');

But you have to make sure that this string ($city_more) won't have more single quotes (') inside it and, if it has, they should be escaped.

EDIT:

Also, if you want to pass more advanced things (arrays, objects etc) from PHP to Javascript, consider using json_encode() in PHP (and also escaping with addslashes()) and $.parseJSON() in Javascript (if you are using jQuery). Like this:

<script>
    var test = $.parseJSON("<?= addslashes(json_encode($array)) ?>");
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top