Reputation: 3223
I am programming beginner..
Code
<script type="text/javascript">
$(function() {
var course_category = "<?php echo $_REQUEST['cities'] ?>";
alert(course_category); // alerts as Array
});
when i do print_r in php (print_r($cities);
) i get
Array ( [0] => BLR [1] => DEL [2] => HYD [3] => MUM
now i want to print the array in above jquery
try
$.each(course_category, function(key,value){
alert(value);
}};
printns A,r,r,a,y
Upvotes: 2
Views: 239
Reputation: 40358
You can use .each
in jQuery to iterate an array
$.each(course_category , function(index, item) {
});
Actually i dont know about php.But you can iterate an array using the above code in jQuery
Upvotes: 0
Reputation: 30293
The correct way is to use JSON:
var list = <?php echo json_encode($_REQUEST['cities']); ?>;
Upvotes: 4
Reputation: 74086
I assume you currently have two problems:
Your PHP array is not encoded in any way, that JavaScript understand. Just use json_encode()
here.
If you receive an object (and arrays are just objects for that matter), you can't just output them using alert()
, if you really want to see the contents. Again, you may use JSON.stringify()
to solve this.
$(function() {
var course_category = "<?php echo json_encode( $_REQUEST['cities'] ); ?>";
alert( JSON.stringify( course_category) );
});
If you want to use the array contents later on, refer to plain for
loops or jQuery's each()
.
Upvotes: 3
Reputation: 7488
<?php
$output = '';
foreach($_REQUEST['cities'] as $city){
$output .= "'$city',";
}
$output = rtrim(",", $output);
?>
var course_category = [<?php echo $output; ?>];
Upvotes: 1