How to insert new data before old data rather than after - javascript

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

Related

how to append more div when refreshing the page

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);

Adding text animation on 'while' PHP

So I have this code below.
<?php
$i = 1;
while($i <= 1000) {
echo "Number : $i <br />";
$i++;
}
?>
I want to add some animation while php creating these array one after another, it's like appearing text animation. Is there any way to do that?
Thanks in advance.
Any help will be much appreciated.
Could do this with JavaScript jQuery.
$(document).ready(function () {
var i = 1;
var int = setInterval(function () {
if (i < 1000) {
var $div = $("<div>Number : "+i+"</div>").hide();
$(".container").append($div);
$div.show(500);
i++;
} else {
clearInterval(int);
}
},1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
</div>
PHP is running on the server, so you cant create an animation using it. You should to use a language which run on the client side, like javascript (or jQuery).
In this post, the user created a Ajax request. While the server is working and the client is waiting for the response, he wanted to show a 'loading spinner': How to show loading spinner in jQuery?

Creating a JSON array from PHP and sending a GET request via JQuery

I'm pulling data from Google Calendar events and wanting to display it in my HTML markup. I've got the data being pulled successfully from Google and thought I was passing it into and array the proper way and encoding into JSON. I was also able to make the GET request via JQuery and confirmed it by checking the console to see if it was received. The problem was trying to display it in the HTML markup.
But, after further debugging, it seems my JSON array isn't correct. Almost as if it duplicates itself everytime it looks for more data from Google.
Here is my code:
<?php
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('google-api-php-client-master/autoload.php');
date_default_timezone_set('America/New_York');
//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar");
$client->setDeveloperKey('my_api_key');
$cal = new Google_Service_Calendar($client);
$calendarId = 'my_calendar_id';
//TELL GOOGLE HOW WE WANT THE EVENTS
$params = array(
'singleEvents' => true, //CAN'T USE TIME MIN WITHOUT THIS, IT SAYS TO TREAT RECURRING EVENTS AS SINGLE EVENTS
'orderBy' => 'startTime',
'timeMin' => date(DateTime::ATOM),//ONLY PULL EVENTS STARTING TODAY
);
$events = $cal->events->listEvents($calendarId, $params);
$count = 0;
$items_to_show = 3;
$data = array();
foreach ($events->getItems() as $event)
{
if($count <= $items_to_show)
{
//Convert date to month and day
$eventDateStr = $event->start->dateTime;
if(empty($eventDateStr))
{
// it's an all day event
$eventDateStr = $event->start->date;
}
$temp_timezone = $event->start->timeZone;
if (!empty($temp_timezone))
{
$timezone = new DateTimeZone($temp_timezone); //GET THE TIME ZONE
}
else
{
$timezone = new DateTimeZone("America/New_York"); //Set your default timezone in case your events don't have one
}
if ($count >= $items_to_show)
{
break;
}
$eventdate = new DateTime($eventDateStr,$timezone);
$data[$count]['newmonth'] = $eventdate->format("M");
$data[$count]['newday'] = $eventdate->format("j");
$data[$count]['newtime'] = $eventdate->format("g:i A");
echo json_encode($data);
++$count; //INCREASE COUNT AND START AGAIN.
}
}
?>
Here is my JSON array (there are only 3 events on the calendar) but it looks like it duplicates or resets everytime it looks for more:
[{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"},{"newmonth":"Jan","newday":"18","newtime":"3:00 AM"}]
Here is my JQuery that I want to display in the HTML automatically:
$(document).ready(function()
{
function load()
{
$.ajax
({
type: 'GET',
url: 'googlesidebar.php',
// data: {key: 'value'},
dataType: 'json',
success: function(data)
{
console.debug(data);
for (var i = 0; i < data.length; i++)
{
$('.newmonth').append(data[i].newmonth),
$('.newday').append(data[i].newday),
$('.newtime').append(data[i].newtime)
};
setTimeout(load, 5000);
},
error: function(data)
{
//called when there is an error
console.log(data.message);
}
});
};
load();
});
HTML Markup:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="newmonth"></div>
<div class="newday"></div>
<div class="newtime"></div>
<footer>
</footer>
<script src="ajax.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Any help would be greatly appreciated!

Automatically update with AJAX

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){

php: make array from pictures in a folder and display them interchangeably?

The following code is supposed to make an array from pictures found in a directory that end in .png using php, then allow buttons to change the pointer on the array and allow the page to display the current picture that the pointer is on. This doesnt seem to be working at all. Am I doing this correctly?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
img {float:left; }
</style>
</head>
<body>
<?PHP
$pages = array ();
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
foreach($images as $image) {
$pages[] = $image;
}
?>
<?PHP
echo '<img src="'.current($pages).'" class="photo"/>';
function shownext() {
$mode = next($pages);
}
function showprev() {
$mode = prev($pages);
}
function showfirst() {
$mode = reset($pages);
}
function showlast() {
$mode = end($pages);
}
?>
first
previous
next
last
</body>
</html>
onclick will allow you to call a javascript function, while your showprev...showlast functions are all php functions. They are not available in javascript's scope.
Also, in your php code:
You are closing the loop right after $pages[] = $image, I think you intend to display (print/echo) all images.
You don't need a loop to copy $pages to $images. You can easily copy it: $pages = $images.
You should be aware that current only makes sense inside a loop and you are calling it after loop is closed.
I think though, that you are confusing server-side (i.e. php) and client-side (i.e. javascript) execution environments.
onclick , uses to trigger javascript functions.
You cant directly put your php functions on onclick="" events. Alternatively, if you want to use jQuery, you could use $.ajax to request the values on PHP. From there, after you got the image paths, manipulate the next, prev, first, last on the client side. Consider this example:
<?php
if(isset($_POST['getimages'])) {
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
// collect the images
foreach($images as $image) {
$pages[] = $image;
}
echo json_encode($pages);
exit;
}
?>
<img src="" alt="" id="images" width="200" height="200" />
<br/>
First
Previous
Next
Last
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var current_pointer = 0;
var images = [];
$.ajax({
url: 'index.php', // call the php file that will process it, i just used this in the same page
type: 'POST',
dataType: 'JSON',
data: {getimages: true},
success: function(response) {
// after a successful response from PHP
// use that data and create your own array in javascript
images = response;
$('#images').attr('src', images[current_pointer]);
}
});
// simple pointer to navigate the array you got from PHP
$('a.navigate').on('click', function(){
var current_val = $(this).attr('id');
switch(current_val) {
case 'first':
current_pointer = 0;
break;
case 'last':
current_pointer = images.length-1;
break;
case 'next':
current_pointer = (current_pointer >= images.length-1) ? images.length-1 : current_pointer+1;
break;
case 'previous':
current_pointer = (current_pointer < 0) ? 0 : current_pointer-1;
break;
}
$('#images').attr('src', images[current_pointer]);
});
});
</script>
The problem is echo '<img src="'.current($pages).'" class="photo"/>';
This will get echoed once, no matter howoften you change $pages afterwards. You also can't call PHP functions with JavaScript's onclick.
PHP will generate the page on server side! On a fully laoded page, most interaction with the user is done via JavaScript.
To achieve your desired result, you have to export the array to JavaScript and change the image src via JavaScript, a little research will help you.

Categories

Resources