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);
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 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
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();
});
I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){
I'm working on twitter bootstrap "data-loading" button.Below posted is my code.The button has to get disabled once it exceeds the page-limit.I was able to do it with normal button that doesnot contain "data-loading" option.Below posted is my code
<head>
<style type="text/css">
* {
font-family:"Times New Roman", Times, serif;
}
</style>
<script>
$(document).ready(function(){
var track_click =0;
var y = <?php echo $y; ?>;
$('#ram').load("fetch_pages.php", {'page':track_click}, function(){track_click++;
});
$('.load_more').on("click",function()
{
if(track_click<=y)
{
$.post('fetch_pages.php',{'page': track_click},function(data){
$('.load_more').show();
$('#ram').append(data);
$("html, body").animate({scrollTop: $("#hi").offset().top}, 500);
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //alert any HTTP error
$(".load_more").show(); //bring back load more button
});
if(track_click >= y-1)
{
$('.load_more').attr('disabled','disabled');
}
}
});
});
$(function() {
$(".btn").click(function(){
var btn = $(this)
btn.button('loading')
setTimeout(function(){
btn.button('reset')},100);
});
});
</script>
</head>
<?php
include 'config.inc.php';
$query = "select count(*) from posts";
$exec = mysqli_query($connecDB,$query);
$ref = mysqli_fetch_array($exec);
echo $item_per_page;
$y=$ref[0];
$k=ceil($y/$item_per_page);
?>
<body>
<div align="center">
<button class=" load_more btn btn-primary" name = "test" id="hi">load
More</button>
</div>
<div id = "ram">
</div>
</body>
</html>
Try using prop instead of attr:
$('.load_more').prop('disabled',true);
If that doesn't solve your problem, you need to check what's in track_click and y, which we can't really do for you without some sort of actual data.
EDIT:
I put your code in jsbin and it seems to run fine with hard coded variables and without the post, so I think it's something wrong with some other part of your code.