increment php variable used in javascript - javascript

I wanted to display a graph in javascript using data from php. My code is:
<?php $i = 20; ?>
while (data.length < totalPoints) {
array_js.push(<?php echo json_encode($array_php[++$i][1]);?>);
}
The problem is that even though $i is declared before the while loop, it gets back to 20 all the time, so the data pushed in array_js is always $array_php[21][1].
Edit: here is more code, (not same variable name...)
startConn(); //connect to database
$query = "SELECT * FROM Reading";
$data = getAllDatas($query);
?>
<script type="text/javascript">
$(function() {
var data = [], totalPoints = 300;
function getRandomData() {
<?php $i = 20; ?>
while (data.length < totalPoints) {
data.push(<?php echo json_encode($data[--$i][1]);?>);
//data.push(<?php echo ++$i;?>);
}
} // END getRandomData()

You have a misunderstanding on how server side and client side code work.
I think this may help you
$(function() {
var data = [], totalPoints = 3;
var i = <?php $i = 1;echo $i; ?>;
var j = parseInt(i);
var arr = <?php echo json_encode($data); ?>;
function getRandomData() {
while (data.length < totalPoints) {
data.push(arr[j][1]);
j++;
}
return data;
}
var data1 = getRandomData();
console.log(data1);
});

Try this one. You can pass the value of the php variable using echo while declaring another variable on the java script.
<?php $i = 20; ?>
var i = <?php echo $i;?>;
while (data.length < totalPoints) {
array_js.push(<?php echo json_encode($array_php[++i][1]);?>);
}

Related

How to Iterate through Object in JavaScript and PHP

I am having to solve a problem involving code in both JS and PHP. For some reason, whenever this code executes, it puts the first entry in all the rows of the table instead of iterating through each entry and putting all of them in the rows. I would appreciate someone's help in giving me insights into how to fix this issue. Can this be fixed with just a "for in" loop? Thanks in advance.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$sql = "SELECT COUNT(`LID`) AS `x` FROM `snipe`.`plobby` WHERE LID = '".$_POST['id']."';";
$result = $db->query($query);
$rst = $db->query($sql);
$cnt = 0;
if($rst->num_rows > 0)
while($row = $rst->fetch_assoc())
$cnt = $row["x"];
if ($result->num_rows > 0)
for($i = 1;$i<= $cnt;$i++)
echo json_encode($result->fetch_assoc());
else
echo json_encode([]);
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is the object to which the above loop is referring:
<script type="text/javascript">
var state = {};
for($i = 1;$i <= <?php echo getLobbytPlayers($_GET['id']);?>;$i++ ){
var reloadTable = function (data) {
if ($.data(state) == $.data(data)) {
return;
}
$('#js-lobby-table').empty();
$.each(data, function (rowNumber, rowData) {
var row = $('<tr>');
console.log(data);
// Player
row.append($('<td>', {
'html': data.eName
}));
// Status
row.append($('<td>', {
'html': data.gameID == "000" ? 'waiting' : 'ingame'
}));
// Win %
row.append($('<td>', {
'html': 'TODO'
}));
// Games
row.append($('<td>', {
'html': 'TODO'
}));
// K/D
row.append($('<td>', {
'html': 'TODO'
}));
$('#js-lobby-table').append(row);
});
// Set the current table state.
state = data;
};
}
setInterval(function () {
$.ajax({
type: 'POST',
url: '/lobby/api/table.php',
data: {
id: '<?= $_GET['id'] ?>'
},
success: reloadTable,
dataType: 'json'
});
}, 10);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You shouldn't call json_encode() multiple times. The response has to contain a single JSON object, not multiple objects. You need to put all the results in an array, and call json_encode() on that array at the end.
There's also no need to get the count first. Just call fetch_assoc() until you get all the results.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$result = $db->query($query);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
?>

Why my script is stop running when i put a variable in foreach and for loop

When i put
$link15 = $link15.$U;
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
this line of code in foreach/for loop the the script is stop after displaying one result. and when i remove this line of code it runs.
Below is the complete script:
for ($i = 0, $count = count($arr1); $i < $count; $i++) {
print $arr1[$i]."\r\n\r\n";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
$result15 = httpGet("https://www.google.com/cse?cx=003255331468891741234:xxxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
//echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
$link15 = $link15.$U;
}
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
}
Where i am doing error in concatenation or any other error.
Thank You!
Based on your code, $U is an object, yet you're trying to concatenate it to $link15.
Try changing this:
$link15 = $link15.$U;
To this:
$link15 = $link15.$U->nodeValue;
You cannot concatenate an object with a string
try the below code (what I have changed is I am accessing the particular key named as "nodeValue" in your $U object. If you want to add another change it accordingly, you need to access the particular key or bunch of keys depending on your requirement)
for ($i = 0, $count = count($arr1); $i < $count; $i++)
{
print $arr1[$i]."\r\n\r\n";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
$result15 = httpGet("https://www.google.com/cse?cx=0032553314688917412345:xxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
//echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
// here you need to access the particular key or bunch of keys depending on your requirement
$link15 = $link15.$U->nodeValue;
}
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
}
Hope this helps.

PHP to JAVA - Database JSON

There are plenty of examples of using database records to disable certain dates (unavailable) using JSON and AJAX however for some reason, these are done in PHP. Is there reason why it isn't done in JAVA and how can I replace the PHP file with Java for the exact same result?
checkDates.php
<? php
$sql = "SELECT start from gbh_rooster_afwijkend WHERE dlnmrID = '".$_GET['dld'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$checkDates = array();
while ($row = mysql_fetch_assoc($res)) {
$checkDate['start'] = $row['start'];
$checkDates[] = $checkDate;
}
echo json_encode($checkDates);
?>
Javascript
$.getJSON('script/php/afwijkendrooster/checkDates.php?dld='+ id, function(json){dates=json;});
function checkAvailability(mydate){
var myBadDates = dates;
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);
// start loop
for(var x in myBadDates)
{
$myBadDates = new Array( myBadDates[x]['start']);
for(var i = 0; i < $myBadDates.length; i++)
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
//end loop
return [$return,$returnclass];
}

PHP Query Array to Javascript Google Maps Iterator

PHP Code
$sql = "SELECT location FROM data";
$result=$conn->query($sql);
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row["location"];
}
Javascript
function getPoints(){
return [
var coordinateArray = <?php echo json_encode($data); ?>;
for(i-0;i<coordinateArray.length; i++({
var sep = coordinateArrays.split(',');
new google.maps.LatLng(sep[0], sep[1]);
}
];
}
Sample data in table:
location = 12.121212,13.131313 -> No quotes
data = "Hello"
author="Me"
Currently it breaks declaring the Array variable in javascript.Something is breaking there. Any help is appreciated
seems you have a name mismatch coordinateArray / coordinateArrays and and index problem try
var coordinateArray = <?php echo json_encode($data); ?>;
for(i=0; i<coordinateArray.length; i++) {
var sep = coordinateArray[i].split(',');
new google.maps.LatLng(sep[0], sep[1]);
}
and also problem with parentesis i++( and assignment i-1 instead of i++) and i=1

Passing the query count in javascript variable

See i have below Code in my javascript
var itemCount = 5, activeScroll = 0, countScroll = 0;
setInterval(function() {
if(countScroll == (itemCount - 2))
{
activeScroll = 0;
countScroll = 0;
$('#list').animate({scrollTop: 0});
}
else
{
activeScroll += 250;
countScroll += 1;
$('#list').animate({scrollTop: activeScroll});
}
}, 2000);
and my query string in php code is
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
i am trying to assign value of $adcount in javascript variable var itemCount;
query is running in test.php and javascript is scroller.js.
Please help me .
You can output javascript by test.php:
<?php
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
?>
<script type='text/javascript'>
var itemCount = <?php echo $adcount; ?>;
setupTimer(itemCount);
</script>
Make sure the scroller.js defines the function setupTimer(itemCount) that performs the task you want, instead of firing right away.
First you need to request the value from the server. Then you can assign it.
var itemCount;
setInterval(function() {
$.get('test.php', function(response) {
itemCount = response.itemCount;
// you scroll logic here
}, 'json');
}, 2000);
In test.php you should output the value by something like this:
$output = array(
"itemCount" => $adcount
);
print json_encode($output);
in scroller.js type this code:
$.ajax("test.php", {
type: 'post',
data: {
count:itemCount
},
sync: true,
success: function (adcount) {
itemCount=adcount;
}
});
in test.phptype this code:
if (isset($_POST['count']))
{
echo $adcount;
exit;
}
notice:you should use jquery file in your script for ajax

Categories