loop through JSON array to generate Multiple Countdown timer? - php

Currently I'm using a jquery count down timer plugin (This Plugin) to generate the Counter through Ajax call .
for now its working fine with no problem for a single call but when i tried to generate a multiple counter whole looping through Json array it doesn't work .
JS
$(document).ready(function(){
$.ajax({
url: 'time.php',
async: false,
dataType: 'json',
success: function(data) {
var response = data ;
$.each(response, function(i, item) {
var time = new Date(item.time) ;
$('.timer').append('<li id='+ i +'></li>');
$('#'+i).countdown({
until: time,
compact: true,
format: 'HMS'
});
});
},
error: function(http, message, exc) {
time = new Date();
}
}
);
})
PHP
<?php
$now = time() + 9999;
$now1 = time()+ 5000;
$data = array($now,$now1);
$json = array();
foreach ($data as $value){
$json[] = array(
'time' => $value
);
}
echo json_encode($json);
?>
this is the Json output
[{"time":1365712506},{"time":1365707507}]
When I tried to show up the result of loop without setting the time it works fine and showing the right result .
But after setting the time and setting the count down timer its shows 00 instead of the counter
00:00:00
00:00:00

You need to multiply the dates with 1000
var time = new Date(item.time*1000);
I also changed the class to ID and added a letter to the iDs of the LIs for non-html5 browsers
DEMO
$(function(){
var response = [{"time":1365712506},{"time":1365707507}];
$.each(response, function(i, item) {
var time = new Date(item.time*1000) ;
$('#timer').append('<li id="t'+ i +'"></li>');
$('#t'+i).countdown({
until: time,
compact: true,
format: 'HMS'
});
});
});

You need to check your dates, I dont believe that they are in the furture.
console.log(time);
Fiddle

Related

My ajax taking too much time in for loop calling a php file

My Ajax is taking too much time on loading am calling ajax from 1 to 3000
It hit on database and get if value exist in database from 1 to 3000 then it will return
Here's my code
function Getdata(e) {
e = e;
jQuery.ajax({
type: "GET",
async: true,
url: "getdata.php",
data: "id=" + e,
success: function(t) {
jQuery(".reult_get_wish-" + e).html(t.htmltext)
},
dataType: "json"
})
}
for (var e = 1; e <= 3000; e++) {
Getdata(e);
}
Here's my getdata.php file code
$id = $_GET['id'];
$sql = "SELECT * from wishing_report where user = '".$id."'";
$result = $mysqli->query($sql);
if ($e = $result->fetch_array(MYSQLI_ASSOC))
{
echo json_encode($e);
}
Explained
If it takes some time, why not use an asynchronous approach, where you can process 'x' amount at a time, i.e. you could use setTimeout and recursion or setInterval, just so you can process a block of information/data at a time.
In this example you can see that there's an onIterate function and a onComplete function, both of these are used in different scenarios, you can use the onIterate function for each iteration, prior to the iterate function being complete. Once you've iterated enough, this is when you can fire the onComplete function, feel free to make any changes you like, i.e. include promises or whatever takes your fancy.
This could also be a better approach for the server as you're allowing the server time to recover from the last request. Alternatively you could alter your back end code so that it's more efficient, etc, you could use some limit and offset parameter(s) within your query to ensure the server isn't handling too much data at one time.
// A function to fire when the ajax request has finished.
const onSuccess = data => {
console.log(data);
};
// Simulate the ajax request.
const getData = (i, callback) => {
setTimeout(() => {
console.log(i);
return callback(i);
}, 500);
}
// A function to fire once complete.
const onComplete = () => console.log('Finished');
// A function to fire if it's not finished/complete.
const onIterate = () => console.log('NOT finished yet');
// A function to iterate, break the loop up into chuncks.
const iterate = (start, end, delay) => {
const process = data => {
iterate(++start, end, delay)
if (start > end) {
onComplete(data);
} else {
onIterate(data);
}
};
if (start <= end) {
setTimeout(() => {
getData(start, process);
}, delay);
}
};
// A starting point.
const start = () => iterate(0, 10, 1500);
// Just start the function.
start();
Your Ajax is taking a lot of time beacause you're running it 3000 times. To avoid calling it many times, I recommend putting all ids in array. I would do something like this.
JavaScript:
function Getdata(e) {
e = e;
jQuery.ajax({
type: "POST",
async: true,
url: "getdata.php",
data: {id: e},
success: function(t) {
$.each(t, function() {
$.each(this, function(k, v) {
jQuery(".reult_get_wish-" + v).html(v.htmltext);
});
});
},
dataType: "json"
})
}
var arr = [];
for (var e = 1; e <= 3000; e++) {
arr.push(e);
}
Getdata(arr);
PHP:
$id = $_POST['id'];
$sql = "SELECT * from wishing_report where user IN ('".implode(',', $id)."')";
$result = $mysqli->query($sql);
if ($e = $result->fetch_array(MYSQLI_ASSOC))
{
echo json_encode($e);
}

Datepicker Unavailable dates (data retrieved from database)

I'm trying to get dates from my database and put them in an array where it would be stored in json.
MAIN.PHP
$('#datepicker').focus(function(){
$.ajax({
url: 'getDates.php',
data: "artist_name="+$('#name').html(),
dataType: 'json',
success: function(data)
{
}
});
})
getDates.php
$fullname = $_GET['artist_name'];
$result = mysql_query("SELECT .... FROM .... WHERE ... ='$fullname'")
$arraydates = array();
while($details = mysql_fetch_assoc($result)) {
array_push($arraydates, $details['event_date']);
}
echo json_encode($arraydates);
I've managed to put all the dates from the selected artist in the "arraydates".
I found this on google:
var unavailableDates = ["21-8-2013"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
That's fine. But now I'm trying to get the results from the array (within getDates.php) and use them in the "main.php". So basically I want to use the data like above with "unavailableDates" array. (and thus, disable the specific dates within the jquery date picker).
Instead of having "unavailableDates", I have the "arraydates". I don't really know how can I use my array inside the "unavailable" function.
I'm not really good with json, actually it's my first time I used json. So could anyone please help me with that?
you can use jquery:
//...
success: function(data){
var arrayLength=data.length;
for(var i=0;i<arrayLength;i++){
if(unavailable(data[i]){
//your code here
}
}
}
//...
The ajax will return $arraydates in a JSON format. Use parse.JSON(returned value)
for example
success: function(data)
{
var unavailableDates = parse.JSON(data);
//Your code ....
}
Hope that helped.

returned json data from table always repeats the one before last

I have a div which uses long polling to update with table data, it all works except when I enter a new piece of text, the text that was inserted before that always appears first and then what I just wrote.
so, if I write hi, hello, goodbye I will get the following:
hi
hi
hello
hello
goodbye
relevant JS:
var timestamp = null;
function waitForMsg() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
if (json['msg']) {
$('.chat_contacts .inner_chat').append(json['msg']+'<br>'); // MD
}
timestamp = json['timestamp'];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('waitForMsg()', 1000);
}
});
}
relevant snippet from update.php
$response = array();
while($row = mysqli_fetch_assoc($r)) {
$nou = $row['f1'];
$nru = $row['f2'];
$response['msg'] = $row['content'];
$response['timestamp'] = $row['time'];
}
echo json_encode($response);
Why doesn't it just detect the last thing entered and display that alone, without repeating the previous data that was entered?
EDIT:
I noticed something.
It also appears to be swallowing what is entered, so if the table is empty, and i write "hi", I get hi, but then if I write "hello", i get "hi" again, and THEN if I write something else I get "hello" (and not what I just wrote) and so on.
Replace $response['msg'] = $row['content']; with $response['msg'][] = $row['content'];
And change below JS code
if (json['msg']) {
$('.chat_contacts .inner_chat').append(json['msg'] + '<br>');
} // MD
With
if (json['msg'].length) {
var el = $('.chat_contacts .inner_chat');
$.each(json['msg'], function(i, v) {
el.append(v + '<br>'); //MD
});
}
And make sure in sql query you are using something like this WHERE time > timestamp

onchange F(x) to php to Highchart on same page

I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Jquery:: Ajax powered progress bar?

I have a page which uses jquery's ajax functions to send some messages.
There could be upwards of 50k messages to send.
This can take some time obviously.
What I am looking to do is show a progress bar with the messages being sent.
The backend is PHP.
How can I do this?
My solution:
Send through a unique identifier in the original ajax call.
This identifier is stored in a database(or a file named with the identifier etc), along with the completion percentage.
This is updated as the original script proceeds.
a function is setup called progress(ident)
The function makes an ajax call to a script that reads the percentage.
the progressbar is updated
If the returned percentage is not 100,
the function sets a timeout that calls itself after 1 second.
Check this if you use jQuery:
http://docs.jquery.com/UI/Progressbar
You can just supply the value of the bar on every AJAX success.
Otherwise, if you don't use JS Framework see this:
http://www.redips.net/javascript/ajax-progress-bar/
I don't have a way to test it, but it should go like this:
var current = 0;
var total = 0;
var total_emails = <?php $total_emails ;?>;
$.ajax({
...
success: function(data) {
current++; // Add one to the current number of processed emails
total = (current/total_emails)*100; // Get the percent of the processed emails
$("#progressbar").progressbar("value", total); // Add the new value to the progress bar
}
});
And make sure that you'll include jQuery along with jQueryUI, and then to add the #progressbar container somewhere on the page.
I may have some errors though ...
You will probably have to round the total, especially if you have a lot of emails.
You could have an animated gif load via .html() into the results area until your ajax function returns back the results. Just an idea.
Regarding the jquery ui progress bar, intermittently through your script you'll want to echo a numeric value representing the percent complete as an assigned javascript variable. For example...
// text example php script
if (isset($_GET['twentyfive-percent'])) {
sleep(2); // I used sleep() to simulate processing
echo '$("#progressbar").progressbar({ value: 25 });';
}
if (isset($_GET['fifty-percent'])) {
sleep(2);
echo '$("#progressbar").progressbar({ value: 50 });';
}
if (isset($_GET['seventyfive-percent'])) {
sleep(2);
echo '$("#progressbar").progressbar({ value: 75 });';
}
if (isset($_GET['onehundred-percent'])) {
sleep(2);
echo '$("#progressbar").progressbar({ value: 100 });';
}
And below is the function I used to get the progress bar to update its position. A little nuts, I know.
avail_elem = 0;
function progress_bar() {
progress_status = $('#progressbar').progressbar('value');
progress_status_avail = ['twentyfive-percent', 'fifty-percent', 'seventyfive-percent', 'onehundred-percent'];
if (progress_status != '100') {
$.ajax({
url: 'test.php?' + progress_status_avail[avail_elem],
success: function(msg) {
eval(msg);
avail_elem++;
progress_bar();
}
});
}
}
If I had to guess, I bet there is a better way... But this is the way it worked for me when I tested it.
Use this answered question
this is how i implemented it:
var progressTrigger;
var progressElem = $('span#progressCounter');
var resultsElem = $('span#results');
var recordCount = 0;
$.ajax({
type: "POST",
url: "Granules.asmx/Search",
data: "{wtk: '" + wkt + "', insideOnly: '" + properties.insideOnly + "', satellites: '" + satIds + "', startDate: '" + strDateFrom + "', endDate: '" + strDateTo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (xml) {
Map.LoadKML(xml);
},
beforeSend: function (thisXHR) {
progressElem.html(" Waiting for response from server ...");
ResultsWindow.LoadingStart();
progressTrigger = setInterval(function () {
if (thisXHR.readyState > 2) {
var totalBytes = thisXHR.getResponseHeader('Content-length');
var dlBytes = thisXHR.responseText.length;
(totalBytes > 0) ? progressElem.html("Downloading: " + Math.round((dlBytes / totalBytes) * 100) + "%") : "Downloading: " + progressElem.html(Math.round(dlBytes / 1024) + "K");
}
}, 200);
},
complete: function () {
clearInterval(progressTrigger);
progressElem.html("");
resultsElem.html(recordCount);
ResultsWindow.LoadingEnd();
},
failure: function (msg) {
var message = new ControlPanel.Message("<p>There was an error on search.</p><p>" + msg + "</p>", ControlPanel.Message.Type.ERROR);
}
});

Categories