Script is not running at the same time as the loop - php

I currently have a for loop and I am running a script inside it.
I logged whenever the loop ran and whenever the function was executed.
This is a sample of my code:
This script is in a loop that runs 3 times
<script>
console.log ("LOOP");
var impressions = [<?= implode(",", $prod_impression_dots) ?>];
var testdata = [
{
"key" : "Impressions" ,
"type": "line",
"values" : impressions,
"yAxis": 1
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
nv.addGraph(function() {
console.log ("Add graph is called here");
console.log (testdata);
var chart = nv.models.multiChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.x(function(d,i) { return i })
.color(d3.scale.category10().range());
chart.xAxis
.tickFormat(function(d) {
var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
if (typeof (dx) == undefined || d > 1000) {
dx = new Date (d);
}
else {
dx = new Date (dx);
}
return dx ? d3.time.format('%x')(dx) : '';
});
chart.yAxis1
.tickFormat(d3.format(',.1f'));
chart.yAxis2
.tickFormat(d3.format(',.4f'));
d3.select('#chart<?= $counter ?> svg')
.datum(testdata)
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
</script>
Below the script is the div tag
<div id='chart<?= $counter ?>' style="width:1150px;height:300px;font-size:11px;margin-top:5px">
<svg> </svg>
</div>
After running this. The output in the console log is as follows;
LOOP
LOOP
LOOP
Add graph is called here
[Object, Object, Object, Object]
Add graph is called here
[Object, Object, Object, Object]
Add graph is called here
[Object, Object, Object, Object]
total 199 nv.d3.js:40
I am just wondering why the function isn't executed right after one iteration of the loop. This causes all the graphs to have the same data.
Thanks.

Definitely your addGraph complete function gets called asynchronously. You can work around this like this.
<script>
console.log ("LOOP");
var impressions = [<?= implode(",", $prod_impression_dots) ?>];
var testdata = [
{
"key" : "Impressions" ,
"type": "line",
"values" : impressions,
"yAxis": 1
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
nv.addGraph((function (testdata) {
return function() {
console.log ("Add graph is called here");
console.log (testdata);
var chart = nv.models.multiChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.x(function(d,i) { return i })
.color(d3.scale.category10().range());
chart.xAxis
.tickFormat(function(d) {
var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
if (typeof (dx) == undefined || d > 1000) {
dx = new Date (d);
}
else {
dx = new Date (dx);
}
return dx ? d3.time.format('%x')(dx) : '';
});
chart.yAxis1
.tickFormat(d3.format(',.1f'));
chart.yAxis2
.tickFormat(d3.format(',.4f'));
d3.select('#chart<?= $counter ?> svg')
.datum(testdata)
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
}
})(testdata));
</script>

Related

Google combo chart issue

I am trying to create a combo chart using google charts,
in HTML added below CDN and div
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: auto; height: 500px;"></div>
the result of
var examname = <?php echo json_encode($examnames); ?>;
var highestScore = <?php echo json_encode($heighestScores); ?>;
var userScore = <?php echo json_encode($userScores); ?>;
is
var examname = ["Test Name 1", "Full Test", "Knowledge"];
var highestScore = ["8", "11", "10"];
var userScore = ["6", "11"];
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var graphData = new google.visualization.DataTable();
graphData.addColumn('string', 'TestName');
graphData.addColumn('number', 'Height');
graphData.addColumn('number', 'YourScore');
for (var i = 0; i < examname.length; i++) {
if (userScore[i] === undefined) {
userScore[i] = 0;
}
console.log(userScore[i]);
graphData.addRow(examname[i], {
v: highestScore[i],
f: userScore[i]
});
}
//graphData = graphData.replace(/'/g, '"');
//var data = google.visualization.arrayToDataTable(graphData);
console.log(data);
var options = {
title: 'Score Dashboard',
vAxis: {
title: 'Score'
},
hAxis: {
title: 'Exam Name'
},
seriesType: 'bars',
series: {
5: {
type: 'line'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(graphData, options);
}
JSFIDDLE
I am getting an error:
Error: If argument is given to addRow, it must be an array, or null
even I searched in google but I didn't understand. Please could any one help me to resolve the issue.
Your passing (string, object). When it's expecting just (array).
Change
graphData.addRow(examname[i], {
v: highestScore[i],
f: userScore[i]
});
To
graphData.addRow([
examname[i],
Number(highestScore[i]),
Number(userScore[i])
]);
Working example: https://jsfiddle.net/g4vjvam9/
Note: If you want the last column filled, you need to add the value :/
var userScore = ["6", "11", "2"];
Also avoid strings else your need to use Number() like above.

Wrong if statement jquery

So I have a counter which counts down to 0 so when it hits 0 I want it to do a pdo update. The problem is that the if statement lets the update happen on each page refresh and does not wait for the count to hit 0.
I have looked at the code and can not see where I am going wrong.
<?php $timer = '20'; ?>
window.onload = function(){
(function(){
var counter = <?php echo $timer ; ?>;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
// Display 'counter' wherever you want to display it.
if (counter === 0) {
document.getElementById( "response" ).innerHTML = "<div style=\"float: right; display: inline-block; margin: 6px;\"><div class=\"skip_btn\">
<?php
$sqll = "UPDATE users SET coins=coins+? WHERE username=?";
$q = $db->prepare($sqll);
$q->execute(array('1',$_SESSION['username']));
$sqll2 = "UPDATE websites SET clicks_left=clicks_left-? WHERE id=?";
$q2 = $db->prepare($sqll2);
$q2->execute(array('1',$row['id']));
?>
</div></div><div style=\"clear:both;\"></div>";
}
}, 1000);
})();
}
I have just fixed it buy using a parser
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('parser.php');
}, 10000);
});
</script>
Thanks for the warm welcome tot he site tho.
Using jQuery try the following:
$(document).ready(function() {
var counter = 20;
setInterval(function() {
if( counter == 0 ) {
$.post("url/to/php");
}
else {
$("#div_for_showing_counter").html(counter);
counter--;
}
}, 1000);
});
This way you separate client side from server side. You can do whatever you want in the php file. If you need a callback or you need to pass data to the php file then simply modify the $.post to something like this:
$.post("url/to/php", { "key1": "value1", "key2": "value2" }, function(data) {
alert(data);
});

Retrieving data from server using jquery $.get function

I am creating a real-time graph with flot library and using jquery $.get function.
I want the graph to be updated every 5 seconds retrieving the recorded data.
The X axis is in time mode. I have been trying to retrieve the necessary data but i can't get it yet. The .php file is fine because it connects to the postgresql database and writes the data into the requested variable.
I think that my problem is in the $.get function.
Can you please help me to find if my Javascript code is fine?
Thanks in advance
<script type="text/javascript">
$(function () {
var data=[];
var data_inicial = [];
var data_actual = [];
var x;
var y;
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; });
data_inicial.push([x]);
return data_inicial;
}
function actualiza_data()
{
$.get("param_pozos_linea2.php", function(data2) { y= data2; });
data_actual.push(y);
return data_actual;
}
// control de velocidad
var updateInterval = 500;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: 100 },
xaxis: { mode: "time",tickLength: 5, timeformat: "%d/%m - %h:%M %p"}
};
var plot = $.plot($("#placeholder"), data_init() , options);
function update() {
plot.setData([ actualiza_data() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
The retrieved data from "param_pozos_linea1.php" file loooks like this:
[1355767803000,0],[1355767502000,0],[1355767202000,0],[1355766902000,0],[1355766602000,0],[1355766302000,0],[1355766002000,0],[1355765702000,0],[1355765402000,0],[1355765103000,2570.17],[1355764803000,2569.63]
And the retrieved data from "param_pozos_linea2.php" looks like this:
[1355767803000,0]
The get request is asynchronous, it is impossible for it to work in a synchronous manner like you think it does.
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; }); <-- calls the server asynchronously
data_inicial.push([x]); <-- is called before code is set on server, so it is setting it with what ever the last value was
return data_inicial; <-- returns something you do not want
}
what you want to do is call the function that set the data
function data_init()
{
$.get("param_pozos_linea1.php",
function(data1) {
data_inicial.push([data1]);
callYourPlotFunction(data_inicial);
}
);
}

change event not working jquery autocomplete

Here is my function i wrote for getting usernames, location, and their pictures. Now the problem is if I use mustMatch option with it, every thing is working fine except for one bug. If lets say i type S it bring 'Sebastian' 'einstain'. If i select sebastian everything works like charm but if i select einstain it erases everything.
I tried to use change: event but its not firing in any case dont know why
$(document).ready(function(){
var wp_v = '3';
$("#searchbox").autocomplete("search.php?wp="+wp_v, {
matchContains: true,
//mustMatch: true,
width: 258,
scroll: true,
scrollHeight: 350,
dataType: 'json',
change: function (event, ui) {
alert('change');
if (!ui.item) {
$(this).val('');
}
},
parse: function(data) {
var array = new Array();
for (var i = 0; i < data.length; i++) {
array[array.length] = {
data: data[i],
value: data[i].name,
result: data[i].name
};
}
return array;
},
formatItem: function(row) {
var output = "<img class=img src='avatars/" + row.img + "'/> ";
output += "<span class=name>"+row.name+"</span><br/>";
output += "<span class=small>"+row.country+"</span><br/>";
return output;
}
}).result(function(event,item) {
if (item == undefined) {
$('#receiver').val('');
} else {
$('#receiver').val(item.uid);
}
});
});
This is the source
[
{"uid":"2","name":"Sebastian Aparicio","img":"1339875067-Koala.jpeg","country":"Leder"},
{"uid":"12","name":"Mester Jakob","img":"default.jpeg","country":"Salg"},
{"uid":"19","name":"Mester Jakob","img":"1339875047-Penguins.jpeg","country":"Leder"}
]
Actually autocomplete plugin version was different. That's why it was not working.

Jquery .Ajax - How to Pass Data

I'm trying to pass a variable via jquery ajax call. I'm not exactly sure how to do it properly. I get the lon lat coordinates through another html5 script.
How do i get the coordinates on the other side? I tried $_GET(lat).
I'm also not sure if i'm able to use the location.coords.latitude in a different < script >.
$.ajax({
cache: false,
url: "mobile/nearby.php",
dataType: "html",
data: "lat="+location.coords.latitude+"&lon="+loc.coords.longitude+,
success: function (data2) {
$("#nearbysgeo").html(data2);
}
});
These scripts are above the jquery code
<script type="text/javascript">
google.setOnLoadCallback(function() {
$(function() {
navigator.geolocation.getCurrentPosition(displayCoordinates);
function displayCoordinates(location) {
var map = new GMap2(document.getElementById("location"));
map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude), 12);
map.setUIToDefault();
var point = new GLatLng(location.coords.latitude, location.coords.longitude);
var marker = new GMarker(point);
map.addOverlay(marker);
}
})
});
</script>
<script type="text/javascript" charset="utf-8">
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome";
}
}
function success(loc){
console.log(loc);
strout = "";
for(l in loc.coords){
//strout += l +" = " +loc.coords[l] + "<br>";
}
strout += '';
strout += '<center><img src="http://maps.google.com/maps/api/staticmap?center='+loc.coords.latitude+','+loc.coords.longitude+'&markers=color:blue%7Clabel:Y%7C'+loc.coords.latitude+','+ loc.coords.longitude+'&zoom=15&size=400x250&sensor=false&center=currentPosition"></center>';
document.getElementById("output").innerHTML = strout;
document.forms['newPostForm'].lat.value = loc.coords.latitude;
document.forms['newPostForm'].lon.value = loc.coords.longitude;
document.getElementById("coords").innerHTML = '';
document.getElementById("coords").innerHTML = 'CURRENT: Lat:' + loc.coords.latitude + ' Lon:' + loc.coords.longitude;
}
function error(err){
document.getElementById("output").innerHTML = err.message;
}
function clearBlog() {
document.getElementById("listview").innerHTML = '';
}
</script>
ADDITIONAL INFO:
It works if I use this line. So i guess i can't use loc.coords.latitude this way.
data: "&lat=43&lon=-79.3",
Well i hacked it for now to get it working. I filled two hidden form elements on the page with lon and lat values. Then used 'document.forms['newPostForm'].lat.value' to create a line like this.
data: "&lat="+document.forms['newPostForm'].lat.value+"&lon="+document.forms['newPostForm'].lon.value,
Still would like an actual solution.
Here's some code from a project I'm working on. Very simple.
$.post("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
You can switch out .post with .get with no other changes, like so:
$.get("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
Data is passed in name value pairs like so.
{ post_action: "getRecentPosts", limit: "10" }
Rewrite:
$.get("mobile/nearby.php", { lat: location.coords.latitude, lon: loc.coords.longitude }, function(data2){
$("#nearbysgeo").html(data2);
});
$lat = preg_replace('#[^0-9\.]#', '', $_GET['lat']);
You probably can use location.coords.latitude if it is defined before.
jQuery.ajax(
{
url : 'mobile/nearby.php',
data : {
'action' : 'update',
'newname' : 'enteredText',
'oldname' : 'original_html',
'userid' : '10'
},
success : function(msg){
if(msg == 1)
{
alert('success');
}
}
});
this is the proper syntax of jQuery.Ajax(); function

Categories