<? foreach ($waiting_users as $waiting_user): ?>
<? echo $waiting_user->user_id; ?>
<? endforeach; ?>
I need to define the user id in a javascript variable. What is the best way of doing something like this?
<script type="text/javascript">
var user_id = "<? echo $waiting_user->user_id; ?>"; <-------------???
var post_id = "<? echo $post_id; ?>";
</script>
EDIT
The foreach returns just one user id. It’s used to display a user that has signed up for a chat. Then I use the code below which is in end.js to delete the user from a table.
DELETE FROM table WHERE user_id = ? AND post_id = ?;
<a class="end" href="#" title="End">End</a>
$(document).ready(function() {
$("a.end").click(function() {
$.post(base_url + "index.php/home/end", { user_id : user_id, post_id : $(this).attr('id') }, function(data)
{
alert(data);
}, "json");
});
});
I would recommend getting the desired data through a service which you could call from javascript using ajax, but your version works too, although it is a bit messy.
If you really want to write php code that generates javascript code, I recommend you pass the whole object to the client side. Just make it a JSON and javascript will interpret it as a native javascript object.
UPDATE
If you only want to pass to the client side only the ids of the users, you should loop the users collection (in php) and store them in an array (or object). Then use the mechanism described above :