How to load more on PHP array? - php

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.

Related

redirect page with parameter and parameter cantrain hide function of next page

i want to redirect my page to another page with hide function on next page. when i click on redirect link then page will be redirect as well as function of next page is also called.
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#block_1').click(function () {
window.location("index1.php");
});
});
</script>
Mat be it is possible in J query
Try a url parameter as such.
window.location("index1.php?loadFunc=true");
The catch the URL parameter from the next page. use the following function to get URL parameters.
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
The on the load of the page,
$(document).ready(function(){
if(getUrlParameter('loadFunc') == 'true'){
runHideFunc();
}
})
redirect with index1.php?hideIt=true;
In index1.php
you can call the hide function like this
$(document).ready(function(){
if(getParameterByName('hideIt') == true) {
$('#someID').hide();
//or use a function which will be called on page load
hideSomething();
}
});
function hideSomething() {
//your hide function
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Trying to get live percentage via json from php

I am trying to update on screen without refresh the current percentage that is updated into a database when the user checks something but failed to accomplish this.
Problem is that in the console I get the error TypeError: a is undefined ..."resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b
and the GET request is repeated infinite. Within the get request, the response is:
{"percentage":null}. An additional problem is that the GET request seams to load complete (like getting the final response) only when the php script finishes.
I checked the database and every time I refresh the database dynamically I can see the percentage updating. So it's not a problem from the PHP or SQL, may be a problem from getter.php (file that is printing the result) and the json script.
Please help me on this issue I checked the entire day + yesterday on how to echo value from database live and tried lots of examples but did not understood complete how to do it (this is mostly related to jquery knob, want to implement it there after success). Your help is much appreciated.
Jquery:
jQuery_1_11_0('#check').on('submit', function (e) {
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
function updates() {
$.getJSON("lib/getter.php", function (data) {
$("#progressbar").empty();
$.each(data.result, function () {
percentage = this['percentage'];
if (percentage = null) {
percentage = 100;
$("#progressbar").html(percentage);
}
});
});
}
});
process.php
$urlsarray = array('google.com', 'yahoo.com', 'bing.com');
// this is a dynamic array created by the user, I am giving just a simple example
$counter = 0;
$total = count($urls1);
$session_id = rand(100000000000000, 999999999999999);
$db->query("INSERT INTO sessions (session_id, percentage) VALUES ('$session_id', '$counter')");
foreach ($urlsarray as $urls) {
doing some things
$counter++;
$percentage = ($counter/$total) * 100;
$db->query("UPDATE sessions SET percentage = '$percentage' WHERE session_id = '$session_id'");
}
$db->query("DELETE FROM sessions WHERE session_id = '$session_id'");
$percentage = 100;
getter.php
include("process.php");
global $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
EDIT 2 UPDATE
function updates() {
$.getJSON("lib/getter.html", function (data) {
$("#progressbar").empty();
$("#progressbar").html(data.percentage);
});
}
EDIT 3
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
//$("#progressbar").empty();
console.log(data);
$("#progressbar").html(data.percentage);
if(data.percentage >= 100){
clearInterval(myInterval);
}
});
}
EDIT 4. changed getter.php
include("process.php");
//global $session_id;
//echo $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
$percentage = (int) $percentage['percentage'];
if ($percentage = 100) {
$percentage = 100;
}
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
and the js script
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0('#check').on('submit', function (e) {
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
var percentage = data.percentage;
$("#progressbar").html(percentage).show();
if(percentage >= 100 || typeof percentage !== 'undefined'){
clearInterval(myInterval);
}
});
}
});
// second script is for posting the result
jQuery_1_11_0('#check').on('submit', function (e) {
var validatef = $("#url").val();
var validaterror = $('#errorvalidate');
if (validatef == 'Enter Domains Separated By New Line -MAX 100 DOMAINS-') {
validaterror.text('Please enter domain names in the text area');
e.preventDefault();
} else {
validaterror.text('');
$.ajax({
type: 'post',
url: 'lib/process.php',
data: $('#check').serialize(),
success: function (data) {
$("#result").html(data); // apple
// $("#progressbar").knob().hide();
}
});
e.preventDefault();
} // ending the else
});
I cant help but wonder:
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
How does this recursion stops? Because to me it seems like this timeout will keep on firing eternally. You really need a timeInterval here, set it to a variable, and clear the interval when 100% has been reached.
Maybe replace the above with:
var myInterval = setInterval(function(){
updates();
}, 1000);
then, on the updates function
if(percentage >= 100){
clearInterval(myInterval);
}
By the way, doing:
if(percentage = null){
...
}
Did you mean to compare using = instead of == ? If you want to verify that percentage is set and is a valid number, it would probably be a good idea to do:
if(typeof percentage !== 'undefined' && !isNaN(parseFloat(percentage)){
...
}
Look at what you're sending back to your JS code from PHP:
echo json_encode(array('percentage' => $percentage));
Literally that'll be
{"percentage":42}
In your JS code, you then have:
$.getJSON("lib/getter.php", function (data) {
^^^^---the data coming back from PHP
....
$.each(data.result, function () {
^^^^^^---since when did you put a "result" key into your array?
For this JS code to work, you'd have to be doing
echo json_encode(array('result' => $percentage));
^^^^^^---note the new key.
And note that since you're sending back a SINGLE object in the JSON, with a single key:value pair, there is literally no point in using your inner $.each() loop. You could just as well have
$("#progressbar").html(data.percentage);

How do I use JQuery $.get() method

How to send an HTTP GET request to a page and get a result back:
This is a piece of code using jquery pagination..I think there is a mistake in my code is to call $.get() on a jquery method.
if(isset($_GET['pages'])) {
$pages = $_GET['pages'];
$i = ($pages - 1) * $num_pages + 1;
.....
<?php echo ''.$i.'' ?>
this Jquery code:
//JQuery
(function($) {
$(document).ready(function(e) {
var main = "data_students.php";
$("#data-students").load(main);
// when the button page is pressed
$('.pages').live("click", function(event){
kd_page = this.id;
$.get(main, {pages: kd_page} ,function(data) {
$("#data-students").html(data).show();
});
});
});
}) (jQuery);
$.get("page.php?vars=values&othervar=othervalue",function(data) {
$("#data-students").html(data).show();
});
You can try this
//send as much paramerters as you wish in $.get(url,data,callback);
$.get("page.php",{vars:values,othervar:othervalue},function(data) {
$("#data-students").html(data).show();
});

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>

Tooltip using jQuery

I have tried to call out my document.getElementByID to get the ID from my current form. But it doesn't hover out the specific text that i input rather than it output '​'. As reference from Tooltip/hover-text in an array, i have amended some stuff but still the tooltip text does not show.
Updated code-
In my html page:
<script>
$(document).ready(function ()
{
var tooltip_Text = $('#tooltip_Text');
var tooltip = $('#tooltip');
$('#Hobby').hover(
function()
{
tooltip.fadeIn(200);
},
function()
{
setTimeout ( function () {
tooltip.fadeOut(200); student.php();
}, 1000);
}
);
$('#Hobby').bind('change', function()
{
student.php('user has changed the value');
});​
});​
</script>
//my list/menu
<select name="OffenceName" id="Hobby" ><span id="Hobby"></span>
<?php $arr = array('', 'cycling', 'badminton', 'jetskiing', 'ice-skating');
for($i = 0; $i < count($arr); $i++)
{
echo "<option value=\"{$arr[$i]}\" {$selected}>{$arr[$i]}</option>\n";
}
?>
</select>
<tool id="tooltip" class="tooltip">
<?php $toolarr = array('','cycling is...', 'badmintion is...', 'jetskiing is...', 'ice-skating is...');
for($t = 0; $t < count($toolarr); $t++)
{
if($toolarr[t] == $arr[i])
{
echo "sample display";
}
}
<span id="tooltip_Text"></span>
​
I can't manage to call out the tooltip text below even if i try to get element by id instead of student.php(); Kindly advise.
You should not select the elements with the native javascript selectors but rather with the jQuery selectors. As is stands, your code cant work, because the methods you call only exist, if your elements are wrapped by the jquery Object.
So instead of
document.getElementById("Hobby").hover(...
use
$("#Hobby").hover(...
Your code should throw a couple errors like these:
TypeError: Object #<HTMLDivElement> has no method 'hover'
EDIT:
couple of errors:
//my list/menu is not a valid HTML-comment
student.php() is not valid either
Try this;
$(document).ready(function ()
{
$("#Hobby").hover(function(){
$("#tooltip").fadeIn("slow");
},
function(){
$("#tooltip").fadeOut();
});
$('#Hobby').change(function() {
$("#tooltip_Text").text("user has changed the value"); // or you can use .html("...") intead of .text("...")
});
});​

Categories