Wrong if statement jquery - php

So I have a counter which counts down to 0 so when it hits 0 I want it to do a pdo update. The problem is that the if statement lets the update happen on each page refresh and does not wait for the count to hit 0.
I have looked at the code and can not see where I am going wrong.
<?php $timer = '20'; ?>
window.onload = function(){
(function(){
var counter = <?php echo $timer ; ?>;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
// Display 'counter' wherever you want to display it.
if (counter === 0) {
document.getElementById( "response" ).innerHTML = "<div style=\"float: right; display: inline-block; margin: 6px;\"><div class=\"skip_btn\">
<?php
$sqll = "UPDATE users SET coins=coins+? WHERE username=?";
$q = $db->prepare($sqll);
$q->execute(array('1',$_SESSION['username']));
$sqll2 = "UPDATE websites SET clicks_left=clicks_left-? WHERE id=?";
$q2 = $db->prepare($sqll2);
$q2->execute(array('1',$row['id']));
?>
</div></div><div style=\"clear:both;\"></div>";
}
}, 1000);
})();
}
I have just fixed it buy using a parser
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('parser.php');
}, 10000);
});
</script>
Thanks for the warm welcome tot he site tho.

Using jQuery try the following:
$(document).ready(function() {
var counter = 20;
setInterval(function() {
if( counter == 0 ) {
$.post("url/to/php");
}
else {
$("#div_for_showing_counter").html(counter);
counter--;
}
}, 1000);
});
This way you separate client side from server side. You can do whatever you want in the php file. If you need a callback or you need to pass data to the php file then simply modify the $.post to something like this:
$.post("url/to/php", { "key1": "value1", "key2": "value2" }, function(data) {
alert(data);
});

Related

Passing 2 datas from AJAX to PHP

So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;

php javascript cleartimeout() not working

I have a setTimeout and clearTimeout where the setTimeout is working fine but clearTimeout is not working, can anyone help me?
code:
<script type="text/javascript">
var i = 0;
var status = setTimeout(function () {
if (i <= 2) {
metrics_status();
i++;
} else {
clearTimeout(status);
};
}, 3000);
</script>
<div id="ReloadMetrics"></div>
You should use clearTimeout outside setTimeout like this
var status;
if(status){
clearTimeout(status);
}
status = setTimeout(function () { }
Example1
Example2
I assume you need setInterval instead. which will call your function in specified intervals, until you call the clearInterval
setTimeout function called only once if it is recursive then you need to call clearTimeout
To call a function multiple times then you use setInterval then you can call clearTimeout
Example of setTimeout and clearTimeout is http://www.w3schools.com/jsref/met_win_cleartimeout.asp
Timing functions http://www.w3schools.com/js/js_timing.asp
take a look on the given example http://jsfiddle.net/jogesh_pi/qTGPT/
<div id="status"></div>
JS:
var i = 0;
var status = setInterval(function() {
if (i <= 5) {
//metrics_status();
document.getElementById('status').innerHTML = i;
} else {
document.getElementById('status').innerHTML = "done";
_clearTime();
}
i++;
}, 1000);
function _clearTime(){
return clearInterval(status);
}
hope this should work according to your need..
I think this will do your purpose. please check
<script type="text/javascript">
var i = 0;
var status;
status = setTimeout(Fun, 3000);
function Fun() {
if (i <= 2) {
metrics_status();
i++;
status = setTimeout(Fun, 3000);
} else {
//clearTimeout(status);
};
}
</script>
<div id="ReloadMetrics"></div>

Javascript/jquery not working in IE8

I'm currently working on a website and it runs correctly in chrome but for some reason IE8 does not want to run any of the javascript/jquery scripts. Even when I call for an alert on page ready, it does not pop up. It is a little sloppy; I've included all of the css and jquery in the actual index.php file and was planning on cleaning it up eventually after I was a little farther along, but enough of my terrible excuses. I've read that a trailing comma after an item can make a website not function correctly in IE, but I cannot find one in my code. I am still learning so I am sure there are many things that could be corrected in my code as well. Sorry for how long it is. Essentially what happens is that all of the hidden divs just hang out and lay overtop one another, and none of the code executes.
<script type="text/javascript">
function video_pop(vimeo_link) {
var vimeo_applet = "";
$('.prompt_inner').text(vimeo_applet);
vimeo_applet = "<div>";
vimeo_applet += "<iframe src=\""+vimeo_link+"\" id=\"vimeo_link\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>";
vimeo_applet += "</div>";
$('.prompt_inner').append(vimeo_applet);
$('.prompt_box').css("margin-left", (-(($('.prompt_inner').width())/2)));
$('.prompt_box').css("visibility", "visible");
$('.prompt_background').css("visibility", "visible");
$('.prompt_box').animate({
opacity: '1'
}, 500);
$('.prompt_background').animate({
opacity: '.95'
}, 500);
}
//MAIN MENU FUNCTIONS
function directors() {
$('.menu').stop().fadeOut(1000).hide();
$('#directors').stop().fadeIn(1000);
$('#col_work').stop().fadeOut(1000).hide();
$('#slideshow_container').stop().fadeIn(1000);
}
function contact() {
$('.menu').stop().fadeOut(1000).hide();
$('#main_contact').stop().fadeIn(1000);
$('#col_work').stop().fadeOut(1000).hide();
$('#slideshow_container').stop().fadeIn(1000);
}
function login() {
$('.menu').stop().fadeOut(1000).hide();
$('#login').stop().fadeIn(1000);
$('#col_work').stop().fadeOut(1000).hide();
$('#slideshow_container').stop().fadeIn(1000);
}
function work() {
$('.menu').stop().fadeOut(1000).hide();
clearInterval(slideshow_int);
$('#slideshow_container').stop().fadeOut(1000).hide();
$('#col_work').stop().fadeIn(1000);
}
function showmenu() {
$('#back_button').stop().fadeOut(1000).hide();
$('#director_set').stop().fadeOut(1000).hide();
$('#holness').stop().hide();
$('#pryce').stop().hide();
$('#ntiri').stop().hide();
$('#quiroz').stop().hide();
$('#col_work').stop().hide();
$('#main_menu').stop().fadeIn(1000);
start_slideshow();
$('#slideshow_container').stop().fadeIn(1000);
}
//DIRECTOR FILES
function director(x) {
$('.menu').stop().fadeOut(1000);
$('#main_menu').stop().fadeOut(1000);
$('#col_work').stop().fadeOut(1000).hide();
clearInterval(slideshow_int);
$('#slideshow_container').stop().fadeOut(1000);
$('#back_button').stop().fadeIn(1000);
$('#director_set').stop().fadeIn(1000);
if (x==="1") {
$('#holness').stop().fadeIn(1000);
}
else if (x==="2") {
$('#pryce').stop().fadeIn(1000);
}
else if (x==="3") {
$('#ntiri').stop().fadeIn(1000);
}
else if (x==="4") {
$('#quiroz').stop().fadeIn(1000);
}
}
function start_slideshow() {
slideshow_int = setInterval(function() {
$('#slides > div:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#slides');
}, 5000);
}
$(document).ready(function() {
//HIDE MENUS
$('.menu').hide();
$('#director_set').hide();
$('#back_button').hide();
$('#holness').stop().hide();
$('#pryce').stop().hide();
$('#ntiri').stop().hide();
$('#quiroz').stop().hide();
$('#col_work').stop().hide();
video_pop("<?php
$query = "SELECT * FROM global WHERE id=1";
$queryobj = mysql_query($query);
$result = mysql_fetch_array($queryobj);
echo $result['ovideo'] ?>");
$('.prompt_background').click(function() {
$('.prompt_box').animate({
opacity: '0'
}, 500, function() {
$('.prompt_box').css("visibility", "hidden");
});
$(this).animate({
opacity: '0'
}, 500, function() {
$(this).css("visibility", "hidden");
var vimeo_applet = "";
$('.prompt_inner').text(vimeo_applet);
});
});
//SLIDESHOW CONTROL
$('#slides > div:gt(0)').hide();
start_slideshow();
//WORK MOUSEOVER
<?php
$queryobj = mysql_query("SELECT * FROM global_thumbnails");
$total_global_thumbs = mysql_num_rows($queryobj);
for ($i=1; $i<=$total_global_thumbs; $i++) {
$queryobj = mysql_query("SELECT * FROM global_thumbnails WHERE position = {$i}");
$result = mysql_fetch_array($queryobj);
$global_still_title = strtoupper($result['title']);
echo "$('#global_stills img:eq(".($i-1).")').mouseover(function() {
$('#global_titles').text(\"{$global_still_title}\");
});
";
}
?>
$('#global_stills img').mouseout(function() {
$('#global_titles').text("");
});
});
</script>
i think instead of this
for ($i=1; $i<=$total_global_thumbs; $i++)
try this
for (var i=1; i<=$total_global_thumbs; i++)
Because Without "var" declarations it won't work in IE8 .
once i also faced the same problem. so after i did this it works for me :)
Try to put all the jQuery between $(document).ready(function() { ... });

How to load more on PHP array?

I use jQuery (I found this code in an answer, tested and working) to show people.php and reload it every 100 seconds. People.php has an array peoples where there are saved name, job, birthday.
As you can see, the output stops at 30 names. How can I have a twitter like button "load more" and show 10 more at a time? Additionally, when there are e.g. 50 more people's name (assuming that the user clicked "load more" twice, will the jQuery timeout reload, returned them at 30 as the beginning ?
<script>
var timerID;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php', function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
How about passing a parameter to the URL in your load(..) call?
$(function () {
var startAt = 0;
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?start_at=' + startAt, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
startAt += 30;
});
}
});
Then in people.php you could get the passed parameter using $_GET:
$start_at = 0;
if (isset($_GET['start_at']) && is_numeric($_GET['start_at'])) {
$start_at = (int) $_GET['start_at'];
}
for ($i = $start_at; $i < min($start_at + 30, sizeof($peoples)); $i++) {
echo $peoples[$i]->name;
}
Well what you could do is save a variable that contains the number of people, this example should give you a good view of what i mean.
<script>
var timerID;
var cap;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?cap='+cap, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
<?php
foreach ($peoples as $people) {
if(++$i > $_GET['cap']) break;
echo $people->name;
}
?>
So all you have to do, is change the cap variable, you could do this easily making a javascript function and call this via a onClick event.

jQuery - Animate & Time interval

<script>
$(document).ready(function() {
$.get("database.php", function(data){
var xp = data + "%";
$('#exp_bg').animate({
width: xp
}, 1500, function() { });
});
});
</script>
Database.php:
<?php
$xp = 50;
$level = 100;
$xp_percent = $xp * 100 / $level;
echo $xp_percent;
?>
What i'm trying to do, is that if $xp_percent increases in database.php, then #exp_bg's width will animate into desired width without refresh.
I tried to do that with time interval, which takes data from database.php every speciefed interval of time, but i failed doing that.
Could anyone help me with that?
Your probably going to have to put it inside a setTimeout function like so:
var refreshId = setInterval(function() {
$.get("database.php", function(data){
var xp = data + "%";
$('#exp_bg').animate({
width: xp
}, 1500, function() { });
});
}, 1000);
This would check every second.

Categories