I have an array like
<?php
$info = array(
"cat",
"dog",
"bear"
);
?>
And I output one String randomly on an overlay like
<script>
var text = '<?php echo $info[array_rand ($info)];?>';
$(function() {
var loading = function() {
var over = '<div id="overlay">' + '<p class="info">' + text + '</p>' + '</div>';
$(over).appendTo('body');
$('#overlay').click(function() {
$(this).remove();
});
$(document).keyup(function(e) {
if (e.which === 27) {
$('#overlay').remove();
}
});
};
$('.wrapper').click(loading);
});
</script>
CSS:
#overlay {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #000;
opacity: 0.90;
height: 200%;
}
.info{
position: absolute;
width: 100%;
top: 25%;
height: 200px;
font-size: 50px;
color: white;
text-align: center;
}
My question is:
How can I update the var text and get a new random string every time the overlay is opened by clicking on the body? Till now the string in var text is only updated when I reload the whole page.
Thanx :)
Print your PHP array in the page using JSON:
<!-- language: lang-php -->
<?php
$info = array(
"cat",
"dog",
"bear"
);
?>
<!-- language: lang-js -->
<script type="text/javascript">
// (it's better to retrieve it in ajax)
var arr = <?php echo json_encode($info); ?>;
// 2. Roll some dice in Javascript
// Math.random returns a random value between 0 and 1
var text = "";
// wrapped in a function so you can pick new random values
function pickRandom() {
// Math.random returns a decimal number, and you need to access arrays using their indexes (0, 1, 2) not decimal numbers. Number.parseInt does the rounding.
text = arr[ Number.parseInt( Math.random()*arr.length ) ];
alert("new random value is: " + text);
}
pickRandom();
</script>
Then the rest of your code should work. Hope this helps.
Doc:
JSON encoding: http://php.net/manual/fr/function.json-encode.php
JS randomness: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
You cannot because PHP is executed on the server side.
When you load the page, it sends to your browser the final HTML, with the result of <?php echo $info[array_rand ($info)];?>.
If security is not an issue (games, banking...) you can use randomness using JavaScript.
Otherwise you can reload the page manually like so:
$('#overlay').click(function() {
// reload the page silently. see also http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
window.location.href = window.location.href;
//$(this).remove();
});
Related
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="uploaded" type="file" />
<input type="submit" value="Upload" />
</form>
<?php
if(isset($_REQUEST['submit'])){
$target = "data/".basename( $_FILES['uploaded']['name']) ;
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
}
?>
I know Javascript, AJAX and JQuery etc very well and I believe an upload progress bar can be created using PHP, AJAX and Javascript etc.
I am surprised how to get the size of upload (meaning each second I want to know, how much of the file is uploaded and how much is remaining, I think it should be possible using AJAX etc) file during upload is in process.
Here is link to the PHP manual but I didn't understand that:
http://php.net/manual/en/session.upload-progress.php
Is there any other method to show the upload progress bar using PHP and AJAX but without use of any external extension of PHP? I don't have access to php.ini
Introduction
The PHP Doc is very detailed it says
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
All the information you require is all ready in the PHP session naming
start_time
content_length
bytes_processed
File Information ( Supports Multiple )
All you need is to extract this information and display it in your HTML form.
Basic Example
a.html
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
var intval = null;
var percentage = 0 ;
function startMonitor() {
$.getJSON('b.php',
function (data) {
if (data) {
percentage = Math.round((data.bytes_processed / data.content_length) * 100);
$("#progressbar").progressbar({value: percentage});
$('#progress-txt').html('Uploading ' + percentage + '%');
}
if(!data || percentage == 100){
$('#progress-txt').html('Complete');
stopInterval();
}
});
}
function startInterval() {
if (intval == null) {
intval = window.setInterval(function () {startMonitor()}, 200)
} else {
stopInterval()
}
}
function stopInterval() {
if (intval != null) {
window.clearInterval(intval)
intval = null;
$("#progressbar").hide();
$('#progress-txt').html('Complete');
}
}
startInterval();
</script>
b.php
session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);
Example with PHP Session Upload Progress
Here is a better optimized version from PHP Session Upload Progress
JavaScript
$('#fileupload').bind('fileuploadsend', function (e, data) {
// This feature is only useful for browsers which rely on the iframe transport:
if (data.dataType.substr(0, 6) === 'iframe') {
// Set PHP's session.upload_progress.name value:
var progressObj = {
name: 'PHP_SESSION_UPLOAD_PROGRESS',
value: (new Date()).getTime() // pseudo unique ID
};
data.formData.push(progressObj);
// Start the progress polling:
data.context.data('interval', setInterval(function () {
$.get('progress.php', $.param([progressObj]), function (result) {
// Trigger a fileupload progress event,
// using the result as progress data:
e = document.createEvent('Event');
e.initEvent('progress', false, true);
$.extend(e, result);
$('#fileupload').data('fileupload')._onProgress(e, data);
}, 'json');
}, 1000)); // poll every second
}
}).bind('fileuploadalways', function (e, data) {
clearInterval(data.context.data('interval'));
});
progress.php
$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
'lengthComputable' => true,
'loaded' => $s['bytes_processed'],
'total' => $s['content_length']
);
echo json_encode($progress);
Other Examples
Tracking Upload Progress with PHP and JavaScript
PHP-5.4-Upload-Progress-Example
This is my code its working fine Try it :
Demo URL (broken link)
http://codesolution.in/dev/jQuery/file_upload_with_progressbar/
Try this below code:
HTML:
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
upload.php :
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
May I suggest you FileDrop.
I used it to make a progess bar, and it's pretty easy.
The only downside I met, is some problems working with large amounts of data, because it dosen't seem to clear up old files -- can be fixed manually.
Not written as JQuery, but it's pretty nice anyway, and the author answers questions pretty fast.
While it may be good fun to write the code for a progress bar, why not choose an existing implementation. Andrew Valums wrote an excellent one and you can find it here:
http://fineuploader.com/
I use it in all my projects and it works like a charm.
First of all, make sure you have PHP 5.4 installed on your machine. You didn't tag php-5.4 so I don't know. Check by calling echo phpversion(); (or php -v from the command line).
Anyway, assuming you have the correct version, you must be able to set the correct values in the php.ini file. Since you say you can't do that, it's not worth me launching into an explanation on how to do it.
As a fallback solution, use a Flash object uploader.
XMLHTTPREQUSET2
var xhr = new XMLHttpRequest();
xhr.open('GET', 'video.avi', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
/*
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
/*...*/
}
};
xhr.addEventListener("progress", updateProgress, false);
xhr.send();
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete)
} else {
// Unable to compute progress information since the total size is unknown
}
}
I made a php script to get random data at one time. I use the refresh function to get more data . However, I only see 1 rows of data and that rows of data is being dynamically updated. I want to get more div from the feed.
In other words, i want to append more div when refresh.
Here is my code below...
<html>
<head>
<title>Add new data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#result {
width: 500px;
height:500px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<pre id="result"></pre>
<script>
const result = document.getElementById("result");
continueExecution();
function continueExecution() {
myVar = setInterval(updateServer, 1000);
}
function updateServer() {
$.get({
url: 'randomData.php',
dataType: 'text',
success: randomdata
});
}
function randomdata(val) {
$('#result').html(val);
}
</script>
</body>
</html>
php script
<?php
$countryarr = array("UNITED STATES", "INDIA", "SINGAPORE","MALAYSIA","COLOMBIA","THAILAND","ALGERIA","ENGLAND","CANADA","CHINA", "SAUDI ARABIA");
$length = sizeof($countryarr)-1;
$random = rand(0,$length);
$random1 = rand(0,$length);
$random_srccountry = $countryarr[$random];
$random_dstcountry = $countryarr[$random1];
echo "<div class='data'>[X] NEW ATTACK: FROM [".$random_srccountry."] TO [".$random_dstcountry."] </div>";
?>
my output from this code
[X] NEW ATTACK: FROM [MALAYSIA] TO [INDIA]
this data continue being updated
I want this output
[X] NEW ATTACK: FROM [MALAYSIA] TO [INDIA]
[X] NEW ATTACK: FROM [ALGERIA] TO [CHINA]
[X] NEW ATTACK: FROM [INDIA] TO [THAILAND]
[X] NEW ATTACK: FROM [ALGERIA] TO [ALGERIA]
My question is how to append more div to the pre tag. Also is it the correct method to input the div in the php script....Please help me. thank you..
if you want to add/append, then use append():
$('#result').append(val);
I perform the php script to show random data. I use ajax get to get data from the php script and continue getting data from the php script every 1 seconds. I also perform removal of the last row if the count is more or eqaul to 4. HOwever, my output is backward. I want to append new data before old data.
php script
<?php
$countryarr = array("UNITED STATES", "INDIA", "SINGAPORE","MALAYSIA","COLOMBIA","THAILAND","ALGERIA","ENGLAND","CANADA","CHINA", "SAUDI ARABIA");
$length = sizeof($countryarr)-1;
$random = rand(0,$length);
$random1 = rand(0,$length);
$random_srccountry = $countryarr[$random];
$random_dstcountry = $countryarr[$random1];
echo "<div>[X] NEW ATTACK: FROM [".$random_srccountry."] TO [".$random_dstcountry."] </div>";
?>
html code
<html>
<head>
<title>Add new data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#result {
width: 500px;
height:500px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
var $auto_refresh = setInterval(function() {
var $count = $('#result div').length;
while ($count >= 4) {
$('result div:last-child').remove();
$count = $('#result div').length;
}
updateServer();
}, 1000);
//Remove last div if the count is more than 4
function updateServer() {
$.get({
url: 'randomData.php',
dataType: 'text',
success: randomdata
});
}
function randomdata(val) {
$('#result').append(val); //i want to insert before in other words new data appear at the top and old data remain down
}
</script>
</body>
</html>
I thought of using before or insertbefore to insert new data before the old data. I also used node to insert before.It does not work. Please help me. thank you..
You have to use prepend() from jquery :
function randomdata(val) {
$('#result').prepend(val);
}
EDIT
I noticed an other error : $('result div:last-child').remove(); should be $('#result div:last-child').remove();
That's probably why it don't change, when it's at 4 divs it doesn't delete and redo the count, so you get stuck inside the while ... The fix from below should solve the problem
What I am trying to do:
I am working on a script intending to offer the user choices and depending on which choice they make, come up with a new choice. I have made two scripts for this, one for my HTML and the structure of my page and one for my PHP (getting the information from my server) and JavaScript (building the generated choices).
I am then using AJAX to communicate between these two scripts, or at least, that's what I am trying to do, but I am very new when it comes to AJAX and I cannot make it work.
I am trying to pass or somehow start the function 'generateProblems' from my page when one of the 3 buttons are pressed, preferably with the param 'id'.
Here's part of my index.html:
<div id="testpile" class="inner cover">
<div id="buttons">
<p><a id="rat" class="btn btn-default" role="button">Rationel</a></p>
<p><a id="emo" class="btn btn-default" role="button">Emotionel</a></p>
<p><a id="per" class="btn btn-default" role="button">Personel</a></p>
</div>
</div>
<div id="testdrop" class="mastfoot">
<p>Drop numbers here</p>
</div>
<script type="text/javascript">
$("#buttons").find(".btn").click(function() {
var id = this.id;
$("#testpile").load("include/responseget.php");
$.post("include/responseget.php", {
choice: "id",
});
});
</script>
And here's my PHP / Javascript:
<?php include 'login.php';
//Query til at finde information til generation af question
$stmt = $conn->prepare("SELECT DISTINCT ResponseTitle, ResponseText FROM response Limit 8;");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$rTitle_array[] = $row['ResponseTitle'];
$rText_array[] = $row['ResponseText'];
}
json_encode($rTitle_array);
json_encode($rText_array);
// close connection
mysqli_close($conn);
?>
<script type="text/javascript">
$(function() {
var phase = 0;
var rTitle = <?php echo json_encode($rTitle_array); ?>;
var rText = <?php echo json_encode($rText_array); ?>;
function generateProblems(param) {
var problemDef = param;
$("#buttons").hide();
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
for (var i = 0; i < 8; i++) {
$('<div>' + rTitle[i] + '</div>').data('number', rTitle[i]).attr('id', 'problem' + rTitle[i]).appendTo('#testpile').draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
});
$('<div>' + rText[i] + '</div>').data('number', rText[i]).attr('id', 'problem' + rText[i]).appendTo('#testpile');
}
$('#testdrop').droppable({
drop: handleDropEvent,
accept: '#testpile div'
});
function handleDropEvent(event, ui) {
var problemNumber = ui.draggable.data('number');
var problemCombination = problemDef + problemNumber;
ui.draggable.draggable('disable');
ui.draggable.draggable('option', 'revert', false);
phase++;
alert('ProblemCombination is "' + problemCombination + '", phase is "' + phase + '" ');
$("#testpile").children().hide();
generateProblems(problemCombination);
}
}
});
</script>
What am I doing wrong? The code worked pretty well before I split it up, but now clicking one of the buttons generate nothing.
This is not the right way to do. Keep your php away from html/js. You can't access to your html from another script which is not directly included in it.
Re-add your javascript part to index.html
In your php script return
something at the end like return json_encode($rTitle_array);
In your
jquery/ajax post, get the returned value and use it
A sample from the jquery doc:
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});
Ok I've been searching and searching for an answer, but have yet to find one in the general area I am looking for. Not being supremely familiar with iScroll (a former developer on this project added it in, and I am now taking it over). I have been trying to figure out where to begin with iScroll.
Right now all seems to work accordingly as far as scrolling up and down. But I want to add some functionality to the overall app thats been developed, such as getting older data and appending it to the more recent data thats listed at that time. An infinite scroll.
Pulling in the data via ajax, and working with it to append it to and refresh iScroll length isn't so much the issue (I think, well for the moment at the least). What is my issue is finding that moment when the bottom is reached and firing off the function I will make to get said data and append it.
I can't find any examples anywhere so I am hoping someone here can throw me some ideas
Since this question is pretty old. This solution is for any future references.
Using iScroll v4.2.5:
var scroll = new iScroll('scroll-wrapper');
scroll.options.onScrollEnd = function(){
if(Math.abs(this.maxScrollY) - Math.abs(this.y) < 10){
// RUN CODE if scroll is 10px from the bottom.
}
};
After along day, i have implemented a smooth infinite scroll and pull to refresh sample app using iscroll4. these two functionality were implemented in one sample app i created. hope its useful to this mobile app developer community.
first it is assumed that:
you are familiar with iscroll4 functions (Not much of a necessity cos am not a guru either).
you know how to make ajax calls to a json file or json/php file
my app summary:
when user loads my app, it makes an ajax call to json/php file on my server and some values are returned.
Problem nature:
i want infinite scrolling alongside pull to refresh functions and i dont want to use any other framework apart from iscroll4.
my solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link href="http://fonts.googleapis.com/css?family=Headland+One%7COpen+Sans:400,300&subset=latin,cyrillic" rel="stylesheet" type="text/css"></link>
<link href="css/mystylesheet.css" rel="stylesheet">
<style>
/**
*
* Horizontal Scrollbar
*
*/
.myScrollbarH {
position:absolute;
z-index:100;
height:8px;
bottom:1px;
left:2px;
right:7px
}
.myScrollbarH > div {
position:absolute;
z-index:100;
height:100%;
/* The following is probably what you want to customize */
background:-webkit-gradient(linear, 0 0, 100% 0, from(#226BF4), to(#226B8F));
background-image:-moz-linear-gradient(top, #226BF4, #226B8F);
background-image:-o-linear-gradient(top, #226BF4, #226B8F);
border:1px solid #226BF4;
-webkit-background-clip:padding-box;
-moz-background-clip:padding-box;
-o-background-clip:padding-box;
background-clip:padding-box;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-o-box-sizing:border-box;
box-sizing:border-box;
-webkit-border-radius:4px;
-moz-border-radius:4px;
-o-border-radius:4px;
border-radius:4px;
-webkit-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
-moz-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
-o-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
}
/**
*
* Vertical Scrollbar
*
*/
.myScrollbarV {
position:absolute;
z-index:100;
width:8px;bottom:7px;top:2px;right:1px
}
.myScrollbarV > div {
position:absolute;
z-index:100;
width:100%;
/* The following is probably what you want to customize */
background:-webkit-gradient(linear, 0 0, 100% 0, from(#226BF4), to(#226B8F));
background-image:-moz-linear-gradient(top, #226BF4, #226B8F);
background-image:-o-linear-gradient(top, #226BF4, #226B8F);
border:1px solid #226BF4;
-webkit-background-clip:padding-box;
-moz-background-clip:padding-box;
-o-background-clip:padding-box;
background-clip:padding-box;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-o-box-sizing:border-box;
box-sizing:border-box;
-webkit-border-radius:4px;
-moz-border-radius:4px;
-o-border-radius:4px;
border-radius:4px;
-webkit-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
-moz-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
-o-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
}
/**
*
* Pull down styles
*
*/
#pullDown, #pullUp {
background:#fff;
height:40px;
line-height:40px;
padding:5px 10px;
border-bottom:1px solid #ccc;
font-weight:bold;
font-size:14px;
color:#888;
}
#pullDown .pullDownIcon, #pullUp .pullUpIcon {
display:block; float:left;
width:40px; height:40px;
background:url(images/pull-icon#2x.png) 0 0 no-repeat;
-webkit-background-size:40px 80px; background-size:40px 80px;
-webkit-transition-property:-webkit-transform;
-webkit-transition-duration:250ms;
}
#pullDown .pullDownIcon {
-webkit-transform:rotate(0deg) translateZ(0);
}
#pullUp .pullUpIcon {
-webkit-transform:rotate(-180deg) translateZ(0);
}
#pullDown.flip .pullDownIcon {
-webkit-transform:rotate(-180deg) translateZ(0);
}
#pullUp.flip .pullUpIcon {
-webkit-transform:rotate(0deg) translateZ(0);
}
#pullDown.loading .pullDownIcon, #pullUp.loading .pullUpIcon {
background-position:0 100%;
-webkit-transform:rotate(0deg) translateZ(0);
-webkit-transition-duration:0ms;
-webkit-animation-name:loading;
-webkit-animation-duration:2s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:linear;
}
#-webkit-keyframes loading {
from { -webkit-transform:rotate(0deg) translateZ(0); }
to { -webkit-transform:rotate(360deg) translateZ(0); }
}
</style>
</head>
<body style="overflow: hidden;" onload="do_refresh();">
<div class="wrap">
<div id="wrapper">
<div id="scroller">
<div id="pullDown">
<span class="pullDownIcon"></span><span class="pullDownLabel">Pull down to refresh...</span>
</div>
<div class="content">
<input type="hidden" id="last_id">
<div id="responsecontainer"></div>
</div>
<span class="load_more_loading" ></span>
</div>
</div>
</div>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script src="js/iscroll.js"></script>
<script src="js/pulltorefresh.js"></script>
<script src="js/infinitescroll.js></script>
<script src="js/myinitialloadscript.js"></script>
<script src="js/mymobileframework.js"></script> <!--independent of this script. eg. whormhole from mosync-->
</body>
</html>
next is to create the myinitialloadscript.js script. this allows content to be loaded into the app for the first time on that page.
function do_refresh()
{
var url = "http://localhost/public_html/landing.php?token=908765789897867567687989089786768980&validator=jhjhjjhjhkhj"; //just url params
// -------------------------------------------
$.ajax({
type: 'GET',
url: url,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
// Evaluate text as a json expression
converters: {"text jsonp": jQuery.parseJSON},
timeout:30000,
async: true,
jsonp: true,
jsonpCallback: "myJsonMethod",
beforeSend: function()
{
//add loading image i dint bcos the image or values becomes double in a case of network delay
$("#responsecontainer").html("images/loader.gif").show();
},
success: function(data)
{
ajax.parseJSONP(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(errorThrown);
alert("Could Not Refresh.");
$("#responsecontainer").html("");//remove loading image
//$("#responsecontainer").load("refresh_h.html"); //load a page with refresh option.
}
});
$.ajaxSetup({ cache: false }); //fetch data from db not cache content
}
//if data is fectched successfully then
var ajax = {
parseJSONP:function(data){
$.each(data, function(i, row) {
if (i==0){
$("#responsecontainer").html('');
}
var ul = '<li>'+row.myjsondatakey+'</li>'; //could be <div></div> This only displays your values from db in a styled manner
$(ul).appendTo('#responsecontainer');// append the value to the responsecontainer
//Now watch closely. remember it was assumed you have a json file or json/php file, and in
//most cases you get your json data format from PHP file. so we assume its from a php file.
//also note that php calls to db can have a LIMIT. so in this case my PHP file data LIMIT
//was set to 5. because of infinite scrolling, i need to know the id of the last element
//from my returned data. so i write the following. note that my row.id_comments which is my
//value i want to get was written into an input whose visibility is hidden. this is to
//enable me over write its value when the last id changes.
if (i==4)
{
//set last id value
$('#last_id').val(row.id_comments);
}
});
}
}
next is to implement pulltorefresh.js much woun't be said about this because the example in iscroll4 is clear.
var myScroll,
pullDownEl, pullDownOffset,
pullUpEl, pullUpOffset,
generatedCount = 0;
function pullDownAction () {
var el;
el = document.getElementById('responsecontainer');
var url = "http://localhost/public_html/landing.php?token=78654567897654356789976546789&valid=jhjhjjhjhkhj";
$.ajax({
type: 'GET',
url: url,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
// Evaluate text as a json expression
converters: {"text jsonp": jQuery.parseJSON},
timeout:30000,
async: true,
jsonp: true,
jsonpCallback: "myJsonMethod",
error: function(){
myScroll.refresh(); //do nofin
},
success: function(data){
//console.dir('success');
ajax.parseJSONP(data);
}
});
$.ajaxSetup({ cache: false }); //fetch data from db not cache content
var ajax = {
parseJSONP:function(data){
$.each(data, function(i, row) {
if (i==0){
$("#responsecontainer").html('');
}
var ul = '<li>'+row.myjsondatakey+'</li>';
$(ul).appendTo(el);
if (i==4)
{
//set last id value
$('#last_id').val(row.id_comments);
}
myScroll.refresh(); // Remember to refresh when contents are loaded (ie: on ajax completion)
});
}
}
}
function loaded() {
pullDownEl = document.getElementById('pullDown');
pullDownOffset = pullDownEl.offsetHeight;
myScroll = new iScroll('wrapper', {
scrollbarClass: 'myScrollbar',
useTransition: true,
topOffset: pullDownOffset,
onRefresh: function () {
if (pullDownEl.className.match('loading')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
}
},
onScrollMove: function () {
if (this.y > 5 && !pullDownEl.className.match('flip')) {
pullDownEl.className = 'flip';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...';
this.minScrollY = 0;
} else if (this.y < 5 && pullDownEl.className.match('flip')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
this.minScrollY = -pullDownOffset;
}
},
//here is where infinite scroll comes in
onScrollEnd: function () {
//infinite scroll started
if(Math.abs(this.maxScrollY) - Math.abs(this.y) < 10)
{
// Do infinite if scroll is 10px from the bottom.
doInfinite_scroll();
}
//infinite scroll ended
if (pullDownEl.className.match('flip')) {
pullDownEl.className = 'loading';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';
pullDownAction(); // Execute custom function (ajax call?)
}
}
});
setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
and last but not the least the main infinitescroll.js recall that we had previously placed a call to this function in pulltorefresh.js where we said if scroll bar is 10px to the end inifite scroll should be triggered. Then we have this as the shot to be fired.
function doInfinite_scroll()
{
var last_id = $('#last_id').val();
var searching = false;
if (!searching) { // only initiate a new ajax request if this variable is false this is to avoid data duplication.
var el;
el = document.getElementById('responsecontainer');
var url = "http://localhost/public_html/landing_more.php?last_id="+last_id+"&token=9876543456789765432456789876543&valid=jhjhjjhjhkhj";
// -------------------------------------------
$.ajax({
type: 'GET',
url: url,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
// Evaluate text as a json expression
converters: {"text jsonp": jQuery.parseJSON},
timeout:30000,
async: true,
jsonp: true,
jsonpCallback: "myJsonMethod",
error: function(){
myScroll.refresh(); //do nofin
},
beforeSend: function()
{
//add loading image i dint bcos the image or values becomes double in a case of network delay
searching = true; // set variable to true
},
success: function(data){
searching = false; // set variable to false
//console.dir('success');
ajax.parseJSONP(data);
}
});
$.ajaxSetup({ cache: false });//fetch data from db not cache content
var ajax = {
parseJSONP:function(data){
$.each(data, function(i, row) {
var ul = '<ul>'+row.comments+'</ul>';
if (i==1) //bcos its php data limit was set to 2 so its always N-1 i.e yourlimit - 1
{
//resset lastdeed id value
$('#lastdeed_id').val(row.id_comments); //update the value in the hidden input field to enable the next set of data load properly
}
$(ul).appendTo(el);
myScroll.refresh(); // Remember to refresh when contents are loaded (ie: on ajax completion)
});
}
}
}
}
so just in case you are lost with what the php file should look like here you go. This file is landing.php
<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');
if ((isset($_GET['token'])) && (isset($_GET['valid']))) {
#require_once('connect/connectionfile.php');
$token=htmlspecialchars($_GET['token'],ENT_QUOTES);
$token= mysql_real_escape_string($token);
$valid=htmlspecialchars($_GET['valid'],ENT_QUOTES);
$valid= mysql_real_escape_string($valid);
//now validating the token
$sql="SELECT * FROM bla WHERE blabla='$token'";
$result=mysql_query($sql);
//if token exists
if(mysql_num_rows($result))
{
header('Content-type: application/json');
//valid token
$fakevalue = mysql_fetch_assoc($result);
$uid = $fakevalue['id'];
$results = array();
$query = "SELECT * FROM bla bal WHERE bla bla bla DESC LIMIT 0, 5";
$rsult = mysql_query($query);
while($value = mysql_fetch_assoc($rsult, MYSQL_ASSOC))
$results[] = $value;
{
echo "myJsonMethod".'('.json_encode($results).')'; //ECHO RESULTS IN JSONP FORMAT
}
}
else
{
//Invalid token
header('Content-type: application/json');
echo "myJsonMethod({\"token\":".utf8_encode(json_encode('failed'))."})";
}
}
else {
header('Content-type: application/json');
echo "myJsonMethod({\"token\":".utf8_encode(json_encode('Invalid token check parameters'))."})";
}
?>
this next file is for infinite scrolling and it is called landing_more.php
<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');
if ((isset($_GET['token'])) && (isset($_GET['validator']))) {
#require_once('connect/connectionfile.php');
$token=htmlspecialchars($_GET['token'],ENT_QUOTES);
$token= mysql_real_escape_string($token);
$validator=htmlspecialchars($_GET['validator'],ENT_QUOTES);
$validator= mysql_real_escape_string($validator);
$last_id=htmlspecialchars($_GET['last_id'],ENT_QUOTES);
$last_id=mysql_real_escape_string($last_id);
//now validating the token
$sql="SELECT * FROM bla WHERE blabla='$token'";
$result=mysql_query($sql);
//if token exists
if(mysql_num_rows($result))
{
header('Content-type: application/json');
//valid token
$fakevalue = mysql_fetch_assoc($result);
$uid = $fakevalue['id'];
$results = array();
$query = "SELECT * FROM bla bla WHERE bla && bla bla && a.id_comments < '$last_id' ORDER BY a.id_comments DESC LIMIT 0, 2";
$rsult = mysql_query($query);
while($value = mysql_fetch_assoc($rsult, MYSQL_ASSOC))
$results[] = $value;
{
echo "myJsonMethod".'('.json_encode($results).')'; //ECHO RESULTS IN JSONP FORMAT
}
}
else
{
//Invalid token
header('Content-type: application/json');
echo "myJsonMethod({\"token\":".utf8_encode(json_encode('failed'))."})";
}
}
else {
header('Content-type: application/json');
echo "myJsonMethod({\"token\":".utf8_encode(json_encode('Invalid token check parameters'))."})";
}
?>