I have a site that plays a stream. I perform an AJAX call to the server once a person presses a button.
<input type="submit" class="play" data-type="<?php echo $result_cameras[$i]["camera_type"]; ?>" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
This prints out a bunch of buttons that the user can select. This is processed by the following code:
<script>
$(document).ready(function(){
$(".play").on('click', function(){
var camerahash = $(this).data('hash');
var cameratype = $(this).data('type');
function doAjax(){
$.ajax({
url: 'index.php?option=streaming&task=playstream&id_hash=<?php echo $id_hash; ?>&camera_hash='+camerahash+'&format=raw',
success: function(data) {
if (data == 'Initializing...please wait')
{
$('#quote p').html(data); //shows a message here
setTimeout(doAjax, 2000);
}
else
{
if (cameratype == "WEBCAM" && data == 'Stream is ready...')
{
$('#quote p').html(data); //another message here
window.location = 'rtsp://<?php echo DEVSTREAMWEB; ?>/<?php echo $session_id;?>/'+camerahash;
}
else if (cameratype == "AXIS" && data == 'Stream is ready...')
{
$('#quote p').html(data); //another message here
window.location = 'rtsp://<?php echo DEVSTREAMIP; ?>/<?php echo $session_id;?>/'+camerahash;
}
else
{
$('#quote p').html(data); //another message here
}
}
}
});
}
doAjax();
});
});
</script>
Everything works as the user gets messages when they click a button. But clicking another button doesn't show the messages any more. I've used the delegate event (.on
) for dynamically loaded buttons (instead of .click()
) which I thought would address this but it looks like I just don't get what I need to do.
on
but you haven't delegated the event handler. Bind it to an ancestor element that is in the DOM at the time the code runs, and pass the selector as the 2nd argument.