I have a system trying to display a graph of a count over time using flot js. The issue I am having is that the graph isnt actually rendering any lines. I have cast the time to UTC and multiplied by 1000 as suggested in other posts but to no avail. Does anyone have any idea what I am doing wrong?
PHP:
public function liveGraphAjax()
{
$query = "SELECT
time as time,
COUNT( id ) as count
FROM table
WHERE HOUR( TIME ) = HOUR( CURRENT_TIME ) -1
GROUP BY DATE_FORMAT(`time`, '%H:%i')";
$result = DB::select($query);
if(isset($result))
{
$temp = array();
foreach ($resultas $row )
{
$temp [] = array(
'time' =>strtotime($row->time) * 1000,
'count' =>(int) $row->count,
);
}
}
return Response::json($temp);
}
JS:
var options = {
colors : [$UpdatingChartColors],
xaxis: {
mode: "time",
timeformat:"%hh:%mm"
},
series: {
lines: { show: true },
points: { show: true }
},
};
$("button.dataUpdate").click(function ()
{
data = [];
$.plot("#updating-chart", data, options);
function fetchData()
{
function onDataReceived(series)
{
var res = [];
data = [series];
for (var i = 0; i < data[0].length; ++i)
{
res.push([data[0][i].time,data[0][i].count]);
}
console.log(res);
$.plot("#updating-chart", res, options);
}
$.ajax({
url: "liveGraphAjax",
type: "GET",
dataType: "json",
success: onDataReceived
});
}
});
The fetchData() function is never called so you never get data.
In your onDataReceived() function the res variable contains only one data series. You have to change your call to $.plot("#updating-chart", [res], options);
Related
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);
}
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...
How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);
I've seen some answers to this question on this site already, but i still haven't been able to implement it as i want to for 2 days now. I'm sort of a beginner so a very clear explanation would be of great help,
i have a mysql database of some data, i want to read from a table and display 30 rows at a time, when the user scrolls to the end of the page, i want to load another 30 rows (i have been able to do the first 30, but loading the remaining is a challenge for me).
i already have this:
$(document).ready(function(){
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() -$(window).height()) {
//ive tried all sorts of things here it just doesnt work
}
});
also an example of the php file that loads the next contents would help,
i'm using php and mysqli
thanks a lot in advance.
so this is my loadmore.php, its for the functionality, haven't styled the output:
<?php
require_once 'functions.php'; //my databse connection is in this file
//i created a function queryMysql($query) in functions.php, thats what is used here
$result = queryMysql("SELECT * FROM articles WHERE live='1' ORDER BY created DESC LIMIT $start, 30");
$num = $result->num_rows;
for ($j = 0 ; $j < $num ; ++$j){
$row = $result->fetch_array(MYSQLI_ASSOC);
$title = $row['title'];
$subtitle = $row['subtitle'];
echo "$title<br />$subtitle";
}?>
for the ajax, i changed it to the first answer i got here, but all my attempts have looked like this:
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: method,
data: {}, //Your data
url: 'loadmore.php',
async: true,
success: function (data, textStatus, jqXHR) {
$('#article-inro-hold').append(data);
},
error: function (jqXHR) {
//Error handler
}
});
}
});
Try to implement jquery ajax, something rough like this:
$(document).ready(function () {
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: method,
data: {}, //Your data
url: 'your/url/to/get/more/content/from',
async: true,
success: function (data, textStatus, jqXHR) {
$('#myDiv').append(data);
},
error: function (jqXHR) {
//Error handler
}
});
}
});
});
You have to make an ajax call for each time, when you scroll amount get up, nearer to document height. Along with you also have to manage your offset, otherwise you will get duplicate records (You can use hidden field for that), and pass it each time in your ajax call.
<div id="ajax-response"></div>
<input type="hidden" value="0" id="offset" />
<script>
$(document).ready(function(){
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
url: 'requesthandler.php',
type: 'post',
data: {
task: 'show-more',
offset: document.getElementById('offset').value
},
success: function(response){
jsonObj = $.parseJSON(response);
$('#ajax-response').append(jsonObj.html);
document.getElementById('offset').value = jsonObj.offset;
}
})
}
});
});
and requesthandler.php will look like:
if($_POST['task'] == 'show-more'){
$offset = (int) $offset;
$sql = "SELECT * FROM table limit $offset, 10";
$data = '';
foreach ($conn->query($sql) as $row) {
$data .= "<div>$row['column']</div>";
}
echo json_encode(array(
'offset' => ($offset + 10),
'html' => $data,
))
}
$query = $db->query("SELECT * FROM bags ORDER BY id DESC LIMIT 7");
Can we use $_POST here to get only needed information.
$limit=($_POST["bag"]);
$query = $db->query("SELECT * FROM bags WHERE id = '.$limit.' ORDER BY id DESC LIMIT 7");
I'm writing a "betting" script so-to-speak, and making an automated system.
The bettor will be able to choose to increase the amount or decrease the amount on win or loss.
The PHP script I wrote returns echo json_encode(array('result' => 'win')); or 'loss' for a loss.
Why won't the below code update that value of the amount dependent upon the result?
$(document).ready(function(){
function updateValuesAuto() {
// Grab all the value just incase they're needed.
var multiplier_auto = $('#multiplier_auto').val();
var percentage_auto = $('#percentage_auto').val();
var bet_amount_auto = $('#bet_amount_auto').val();
var profit_amount_auto = $('#profit_amount_auto').val();
multiplier_auto = (100-1)/percentage_auto;
profit_amount_auto = (bet_amount_auto*multiplier_auto)-bet_amount_auto;
$('#multiplier_auto').val(multiplier_auto);
$('#percentage_auto').val(percentage_auto);
$('#bet_amount_auto').val(bet_amount_auto);
$('#profit_amount_auto').val(profit_amount_auto);
}
$('#multiplier_auto').keyup(updateValuesAuto);
$('#percentage_auto').keyup(updateValuesAuto);
$('#bet_amount_auto').keyup(updateValuesAuto);
$('#profit_amount_auto').keyup(updateValuesAuto);
var runI = null;
var $run = $('#start');
var $times = $('#amount_bets');
var $stop = $('#stop');
$run.on('click', function() {
event.preventDefault();
$(this).attr('disabled', true);
$stop.attr('disabled', false);
var ran = 0;
var val = parseInt($times.val(), 10);
if(isNaN(val) || val === 0 ) return false;
runI = setInterval(function() {
if( ran < val ) {
$.ajax({
url: './requests/bet.php',
type: 'POST',
data: { amount: $('#bet_amount_auto').val(), chance: $('#percentage_auto').val(), multiplier: $('#multiplier_auto').val(), profit: $('#profit_amount_auto').val() },
}).done(function(result) {
var result = JSON.parse(result);
if( result === 'win' ) {
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#wini').val();
}
else if( result === 'loss' ) {
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#lossi').val();
}
ran++;
});
}
else {
clearInterval(runI);
$run.attr('disabled', false);
}
}, 500);
});
$stop.on('click', function() {
event.preventDefault();
clearInterval(runI);
$run.attr('disabled', false);
});
});
Thanks.
You may want to trim down the code to the specifics of the problem if the answer does not help, but would behoove you to actually look at the data that gets sent back. It will be:
{"result":"win"}
So to access the result in the .done function, you'd need to use result.result.
Additionally, if you are sending JSON back, jQuery may be parsing it automatically and JSON.parse may result in an error. To get jQuery to do this, send the JSON content-type header via PHP:
header("Content-type: application/json");
I believe the problem is === because three equals is a strict operator which means value and type must be equal.
In your case it seems you're trying to make sure that result is type of JSON and equals to STRING
Try double-equals == maybe?
EDIT:
Oh got that now...
Actually, you can't assign value to the result of a function. So,
Change this:
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#wini').val();
to
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#wini').val());
Two things:
1.You cannot set value to functions (You cannot put functions in the left side of an assignment)
2.result is JSON and you need to use result.result
$.ajax({
url: './requests/bet.php',
type: 'POST',
data: { amount: $('#bet_amount_auto').val(), chance: $('#percentage_auto').val(), multiplier: $('#multiplier_auto').val(), profit: $('#profit_amount_auto').val() },
}).done(function(result) {
if( result.result === 'win' ) {
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#wini').val()) ;
}
else if( result.result === 'loss' ) {
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#lossi').val()) ;
}
ran++;
});