JavaScript setInterval() and setTimeout() freezing browser - javascript

I'm woking in a mobile friendly monitoring tool based on rrdtool.
All working fine but when I have the webpage opened for more that 1 hour freezes my computer.
I use this snippet for refresh the images.
<?php
if(!isset($includeCheck))
{
exit ("No tienes permisos para ver directamente el archivo");
}
//echo "
//<script language='JavaScript'>
// function refreshIt(element) {
// setTimeout(function() {
// element.src = element.src.split('?')[0] + '?' + new Date().getTime();
// refreshIt(element);
// }, 50000);
// }
//</script>";
echo "
<script language='JavaScript'>
function refreshIt(element){
setInterval(function() {
element.src = element.src.split('?')[0] + '?' + new Date().getTime();
}, 50000);
}
</script>";
?>
I include this php file in the pages what I have images and I want to refresh.
I tried the 2 options but as I said, freezes my browser.
Anyone have idea what can I do? Because I need refresh the images only, I don't want to refres the whole page.
EDIT
Here is the PHP script for print all images in database.
<?php
if(!isset($includeCheck))
{
exit ("No tienes permisos para ver directamente el archivo");
}
if(isset($_GET['freq'])){
$freq = $_GET['freq'];
$title = 'Gráficas';
} else {
exit ("No has especificado la frecuencia");
}
if($freq == "hourly"){
$title = 'Tráfico última hora';
}
if($freq == "daily"){
$title = 'Tráfico último dia';
}
if($freq == "weekly"){
$title = 'Tráfico última semana';
}
if($freq == "monthly"){
$title = 'Tráfico último mes';
}
if($freq == "yearly"){
$title = 'Tráfico último año';
}
if(isset($_GET['limit'])){
$limit = $_GET['limit'];
} else {
$limit="10";
}
if(isset($_GET['inicio'])){
$inicio = $_GET['inicio'];
}
if(isset($_GET['subpage'])){
$subpage = $_GET['subpage'];
if ($subpage==1) {
$inicio=0;
}
} else {
$subpage = "1";
$inicio="0";
}
$total_records = $conn->query("SELECT graph_id FROM graph_".$freq)->num_rows;
$total_pages = ceil($total_records / $limit);
$sql = "SELECT graph_desc,graph_id,graph_name FROM graph_".$freq." ORDER BY graph_desc ASC LIMIT ".$limit." OFFSET ".$inicio.";";
$result = $conn->query($sql);
include_once 'adm/includes/pagination.php';
echo "<h1 id='titulo' class=\"page-header\">".$title."</h1>";
include_once 'adm/includes/refresh.php';
if ($total_pages != '1') {
echo "<div id='pager1' class='col-md-12'>";
echo $pagLink;
echo "</div>";
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<div class='graphSize' style='float:left; position:relative; z-index: 10;'>
<a href='?page=GraphDetail&graph_id=".$row['graph_id']."&graph_desc=".$row['graph_desc']."'>
<img style='width:100%' src='/graficas/".$freq."/".$row['graph_name']."' onload='refreshIt(this)'></img>
</a>
</div>
";
}
}
else {
echo "<p>No hay ninguna gráfica para mostrar</p>"; }
if ($total_pages != '1') {
echo "<div id='pager2' class='col-md-12'>";
echo $pagLink;
echo "</div>";
}
echo "</body>";
if(isset($_GET['fullscreen'])){
echo "<style>";
echo ".graphSize {";
echo "width:500px;";
echo "}";
echo "</style>";
}
$conn->close();

You have this onload handler for your image:
refreshIt(this)
...and that sets an interval (meaning it will repeat) every 50 seconds. The callback for that interval sets the src for the image, which means that onload will once again trigger, and you'll again do a set interval. So each time a new version of the image loads, you add another interval, so eventually you'll have tons of duplicating callbacks occurring.
You probably want to use setTimeout, or call refreshIt(this) once, not on every onload.

Related

Detect time from Wordpress

i hope this is the correct place to ask this. I'm working with a Wordpress theme which detects opening times of a business from a custom field, compares it to the current day and time and then displays a message to say if the business is currently open. This works perfectly in English, but when i change the site language to Spanish using qTranslate X Plugin, the business permanently appears as not open. I really have limited skills at this kinda thing, so i'm hoping someone can advise me.
From what i can see this is the js that does the comparison.
<?php
/* ============== Check TIme ============ */
if (!function_exists('listingpro_check_time')) {
function listingpro_check_time($postid,$status = false) {
$output='';
$buisness_hours = listing_get_metabox_by_ID('business_hours', $postid);
if(!empty($buisness_hours)){
if(!empty($postid)){
$lat = listing_get_metabox_by_ID('latitude',$postid);
$long = listing_get_metabox_by_ID('longitude',$postid);
}
//$timezone = getClosestTimezone($lat, $long);
$timezone = get_option('gmt_offset');
$time = gmdate("H:i", time() + 3600*($timezone+date("I")));
$day = gmdate("l");
$time = strtotime($time);
$lang = get_locale();
setlocale(LC_ALL, $lang.'.utf-8');
$day = strftime("%A");
$day = ucfirst($day);
foreach($buisness_hours as $key=>$value){
if($day == $key){
$dayName = esc_html__('Today','listingpro');
}else{
$dayName = $key;
}
$open = $value['open'];
$open = str_replace(' ', '', $open);
$close = $value['close'];
$close = str_replace(' ', '', $close);
$open = strtotime($open);
$close = strtotime($close);
$newTimeOpen = date('h:i A', $open);
$newTimeClose = date('h:i A', $close);
if($day == $key){
if($time > $open && $time < $close){
if($status == false){
$output = '<span class="grid-opened">'.esc_html__('Open Now~','listingpro').'</span>';
}else{
$output = 'open';
}
}else{
if($status == false){
$output = '<span class="grid-closed">'.esc_html__('Closed Now!','listingpro').'</span>';
}else{
$output = 'close';
}
}
}
}
}else{
if($status == true){
$output = 'open';
}
}
return $output;
}
}
Any direction would be greatly appreciated.

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

Alert box is not showing in codeigniter models

in the model alert is not working. if condition is working,the only problem with the alert box, its not showing the dialog box.Please help..
public function setJumlahPenumpang ($idJadwal,$idPemesanan,$jml,$booked,$selected){
$data1 = $this->db->query('select p.jumlah_kursi, j.jumlah_penumpang, p.harga from tb_po p JOIN tb_jadwal j ON j.id_po = p.id_bus WHERE j.id_jadwal ='. $idJadwal);
foreach ($data1->result_array() as $dataa1) {
$tersedia = $dataa1['jumlah_kursi'] - $dataa1['jumlah_penumpang'];
if($tersedia < $jml){
?>
<script type="text/javascript">
document.location = '<?php echo base_url(); ?>proses/cekKode1/<?php echo $idPemesanan ?>';
alert("Tidak ada Bus Beroperasi");
</script>
<?php
}else{
$data3 = $dataa1['harga'] * $jml;
$this->db->query('update tb_pemesanan set harga = '.$data3.' where id_pemesanan = '.$idPemesanan);
$data = $this->db->query('select jumlah_penumpang from tb_jadwal where id_jadwal ='. $idJadwal);
$this->db->query("update tb_jadwal set booked = '".$booked."' where id_jadwal = ".$idJadwal);
$this->db->query("update tb_pemesanan set kursi = '".$selected."' where id_pemesanan = ".$idPemesanan);
foreach ($data->result_array() as $dataa) {
$data2 = $dataa['jumlah_penumpang'] + $jml;
$this->db->query('update tb_jadwal set jumlah_penumpang = '.$data2.' where id_jadwal = '.$idJadwal);
}
}
}
}
Try Echo Before Script Tag I hope So it 'll work....
if($package_id == NULL) {
echo '<script type="text/javascript">
window.location.href = "'.base_url().'"
</script>';
return;
die();
}

Alert error message gets displayed multiple times

The code is shown below:
if(isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if($img_size > 3000000) {
$error = 'Image should be less than 4 MB';
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
}
}
?>
<script type="text/javascript">
if('<?php echo $error; ?>' != '' && '<?php echo $error; ?>' != undefined) {
alert("<?php echo $error; ?>");
}
</script>
Problem is that whenever I upload an unsupported image type like a .tiff image, the alert box gets displayed. This works the way I want it to work. But if i reload it, then it displays the alert box once again with the same message. It doesn't show up the third time I reload. I want alert message to show up only once, not twice or thrice..
change code to:
<?php
if(isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if($img_size > 3000000) {
$error = 'Image should be less than 4 MB';
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
}
}
if(isset($error)){
?>
<script type="text/javascript">
alert("<?php echo $error; ?>");
</script>
<?php
}
?>
OR
<?php
if(isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if($img_size > 3000000) {
$error = 'Image should be less than 4 MB';
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
}
}
if(isset($error)){
echo "<script type='text/javascript'> alert('<?php echo $error; ?>'); </script>";
}
?>

Update data through checkbox using jquery

I can't get this to work. I need to update the value of a column of the checked checkboxes in mysql. When I click the button it is supposed to update the value of the checked checkboxes. Here is my code for editLayout.php:
<form action="updateLayout.php" method="POST">
<input name="update" type="SUBMIT" value="Update" id="update">
<?php
$x = 'seats';
$linkID = # mysql_connect("localhost", "root", "Newpass123#") or die("Could not connect to MySQL server");
# mysql_select_db("seatmapping") or die("Could not select database");
/* Create and execute query. */
$query = "SELECT * from $x order by rowId, columnId desc";
$result = mysql_query($query);
$prevRowId = null;
$seatColor = null;
$tableRow = false;
//echo $result;
echo "<table class='map'>";
while (list($rowId, $columnId, $status, $name, $seatid) = mysql_fetch_row($result))
{
if ($prevRowId != $rowId) {
if ($rowId != 'A') {
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table><tr>";
} else {
$tableRow = false;
}
if ($status == 0) {
$seatColor = "#A6E22E";
}
else if ($status == 1){
$seatColor = "#D34836";
}
else if ($status == 2){
$seatColor = "#00A0D1";
}
echo "\n<td bgcolor='$seatColor'>";
echo $seatid;
echo "<input type='checkbox' name='seats[]' id='seats' value=".$seatid."> </checkbox>";
echo "</td>";
}
echo "</tr></table></td>";
echo "</tr>";
echo "</form>";
echo "</table>";
/* Close connection to database server. */
mysql_close();
?>
And here is my code for the jquery residing on different page (functions.js). I already included this in the header:
jQuery(function($) {
$("form input[id='update']").click(function() {
var count_checked = $("[name='seats[]']:checked").length;
if(count_checked == 0) {
alert("Please select product(s) to update.");
return false;
}
if(count_checked == 1) {
return confirm("Are you sure you want to update these product?");
} else {
return confirm("Are you sure you want to update these products?");
}
});
});
And here is my updateLayout.php.:
<?php
$db = mysql_connect("localhost", "root", "Newpass123#");
if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("seatmapping");
if(!$select_db) { echo mysql_error(); }
if(isset($_POST['update'])) {
$id_array = $_POST['seats'];
$id_count = count($_POST['seats']);
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
header("Location: editLayout.php");
}
?>
I'm using jquery 1.11.0. I know there's a lot of sql injection in here and im still using mysql but I plan to change it all once I get this to work. Any kind of help is appreciated.
Thanks in advance.
Your update query doesn't use the correct update value. You use '$seatid', which isn't declared anywhere. You should use '$id'.
Change
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
into
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$id'");
if(!$query) { die(mysql_error()); }
}

Categories