Arrays in php & javascript syntax issues - php

I have got my self confused on how to construct arrays correctly in PHP prior to my json encode to check them in javascript.
I'm trying to store an array of objects with their grid reference (x,y)
So i do this in php:
$get = mysql_query("SELECT x,y,sid FROM $table WHERE uid='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($get)) {
$data[$row['x'].$row['y']] = $row['sid'];
}
//print_r($data);
$data = json_encode($data);
In javascript i then try to check if a object exists on a given co-ordinate so i try this:
for (i=0;i<tilesw;i++){ //horizontal
for (j=0;j<tilesh;j++){ // vertical
if(sdata[i.j]){
alert(sdata[i.j][sid]);
}
}
}
sdata is my array after json encode.
My json encode looks like this:
{"44":"0","21":"0"}
Problem is i get :
Uncaught SyntaxError: Unexpected token ] on the alert line.
Also is my approach correct or is there a better way to construct my array?

You have a JavaScript syntax error in your code. There is an extra ] on your alert() line.
alert(sdata[i.j][sid]]);
Should be
alert(sdata[i.j][sid]);
If you're actually trying to concatenate the values i and j you also need to be using + rather than ., so you would use i.toString()+j.toString() as the key rather than i.j.
Example of using this with two-dimensional arrays:
PHP
$arr = array();
while($row = mysql_fetch_assoc($get)) {
if(!isset($arr[$row['x']])) $arr[$row['x']] = array();
$arr[$row['x']][$row['y']] = $row['sid'];
}
$data = json_encode($arr);
JavaScript
for(var x in sdata) {
for(var y in sdata[x]) {
alert('Object found at coordinates ' + x + ',' + y + ' ' + sdata[x][y]);
}
}

Related

D3js Multi line graph convert from using CSV file

I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.

Return to ajax with while loop through PHP

I have got this ajax
$.ajax({
type: "GET",
url: '../connect.php',
data: "OrB=" + ajaxsend+"&&IOr="+i,
success: function(data)
{
var x = $.parseJSON(data);
var el='<div class="CommentsAw Comment_Hs">\
<img src="../users/'+x[0]+'">\
<span>'+x[1]+'</span>\
<span class="s2">'+x[2]+'</span>\
</div>'
$(".F_W_comments").html().remove();
$(".F_W_comments").html(el);
}
});
and php
if (isset($_GET['OrB'])) {
$OB=$_GET['OrB'];
$I=$_GET['IOr'];
if ($OB=='OO') {
$OB='`Date` ASC';
}else if ($OB=='No') {
$OB='`Date` DESC';
}
$query=$con->query("SELECT id,comment FROM uploads WHERE Rand='$I'");
$row=$query->fetch_row();
$Commentsq=$con->query("SELECT * FROM (SELECT * FROM comments WHERE Post_id='$row[0]' ORDER BY $OB LIMIT 4) AS sub ORDER BY `DATE` ASC") or die($con->error);
while ($CommentRow=$Commentsq->fetch_row()) {
$CommenterPp=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$CommentRow[3]'");
$CommenterPicture=$CommenterPp->fetch_row();
$CommenterPp=$con->query("SELECT Username FROM users WHERE Id='$CommentRow[3]'");
$CommenterName=$CommenterPp->fetch_row();
echo json_encode(array($CommenterPicture,$CommenterName,$CommentRow));
}
}
But it gives me error in console like this one
VM654:2 Uncaught SyntaxError: Unexpected token [ in JSON at position 107
[["5734919677561.jpg"],["Murad"],["1842","3","21","1","2016-05-08 21:56:52"]]
[["5734919677561.jpg"],["Murad"],["1843","GOodm","21","1","2016-05-08 21:56:54"]]
[["5734919677561.jpg"],["Murad"],["1845","re","21","1","2016-05-08 21:56:54"]]
[["5734919677561.jpg"],["Murad"],["1844","re","21","1","2016-05-08 21:56:54"]]
What i want is connect.php to get data from database and then pass it to ajax.
But the result was nothing probably bcause there is some error in my code
Echoing several json-encoded strings does not mean a valid json.
What you need to do is json_encode your data and echo it once.
$commenters = array(); // result array
while ($CommentRow=$Commentsq->fetch_row()) {
$CommenterPp=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$CommentRow[3]'");
$CommenterPicture=$CommenterPp->fetch_row();
$CommenterPp=$con->query("SELECT Username FROM users WHERE Id='$CommentRow[3]'");
$CommenterName=$CommenterPp->fetch_row();
$commenters[] = array($CommenterPicture,$CommenterName,$CommentRow);
}
// while loop over
echo json_encode($commenters);
And in your js you should iterate over an array of objects, not a simple object, for example:
success: function(data) {
var x = $.parseJSON(data);
for (var k in x) {
console.log(x[k]);
}
}
Removing the data in the arrays for a moment, the resulting JSON was structured like this:
[][][][]
That's not valid JSON. The parser expects a single object or array, not several arrays concatenated together like that.
Instead of outputting the response in the loop, build the total response and output it once after the loop. Basically create an empty array before the while loop in PHP, then push elements onto the array within the loop, then echo the JSON-encoded array after the loop.
My PHP is very rusty, but in PHP-ish pseudo-code it would be structured like this:
$result = array();
while ($CommentRow=$Commentsq->fetch_row()) {
// other code...
$result[] = array($CommenterPicture,$CommenterName,$CommentRow);
}
echo json_encode($result);

Getting a "syntaxError: JSON.parse: expected ',' or ']' after array element at line x column x" when adding a leading zero to single digit numbers

i am using dataTables to display data from a MySQL database by using PHP, Ajax, and jQuery.
The data i am showing are numbers and everything works fine.
Here is my php script
require_once '../core/init4ajax.php';
$loteria=$_POST['loteria'];
$lotto = new Lotto();
$ultimos_resultados=$lotto->last_results($loteria,20);
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
return array_map(__FUNCTION__, $d);
} else {
// Return array
return $d;
}
}
$new_array = objectToArray($ultimos_resultados);
$result = array();
echo '[';
foreach ($new_array as $new_array2) {
echo '[';
foreach ($new_array2 AS $value){
/********The following piece of code is used to add a leading zero to single digit numbers********/
/*if (1 == strlen($value)) {
$zero=0;
$value = $zero.$value;
}*/
echo $value;
if($value!==end($new_array2)){ //referencias: http://stackoverflow.com/a/8780881/1883256
echo',';
}
}
echo ']';//referencias: http://www.mydigitallife.info/how-to-access-php-array-and-multidimensional-nested-arrays-code-syntax/
if($new_array2!==end($new_array)){
echo ',';
}else{ echo '';}
}
echo ']';
Here is the output sample of the php script:
[[2740,3,9,21,27,46,48],[2741,3,4,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]
And here is the ajax code.
$(document).ready(function() {
$.ajax({
url: "ajax/default_chart_numbers_table.php",
type: "post",
data: {loteria: 'melate'},
success : function (resp){
// would look something like ['val1','val2', 'etc']
var column_data = $.parseJSON(resp);
//alert(column_data);
// adding data to datatables
for (var j=0;j<=column_data.length-1;j++){
// adding each row with its column data
//iterating values to add leading zeros to single digits:
$('#dataTables-melate').dataTable().fnAddData(column_data[j]);
}
},
error: function(jqXHR, textStatus, ex) {
console.log(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
} );
I have realized that i want the single digit numbers to be lead by a zero, e.g. 4, should be shown as 04.
By adding the code in order to add a leading zero (this piece of code is already in my php code but commented):
if (1 == strlen($value)) {
$zero=0;
$value = $zero.$value;
}
Now the php code returns the array the way i want it:
[[2740,03,09,21,27,46,48],[2741,03,04,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]
however, now from the ajax script i get the following error:
SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 9 of the JSON data
and the data is no longer displayed in the dataTables.
Why is this happening? How can i fix it?
I HAVE FIXED IT:
I just had to add double quotes to those single edit numbers:
if (1 == strlen($value)) {
$zero=0;
$value = '"'.$zero.$value.'"';
}
And that did the trick! ☺
It has nothing to do with the leading zeros. This is because you treat the output as JSON, which it is not. It is an array of arrays. The error is caused by the line :
var column_data = $.parseJSON(resp);
Try test the output / supposed JSON with http://jsonlint.com. Example how it could work :
var column_data = [
[2740,3,9,21,27,46,48],
[2741,3,4,13,22,27,29],
[2757,32,34,35,36,50,55]
];
var dataTable = $('#dataTables-melate').dataTable()
for (var j=0;j<=column_data.length-1;j++){
// adding each row with its column data
//iterating values to add leading zeros to single digits:
dataTable.fnAddData(column_data[j]);
}
see demo -> http://jsfiddle.net/jPLSf/
Adding a leading zero changes a javascript "number" to a "string". So JSON.parse returns an error expecting numbers (eg: 4) but instead sees a string (eg: "04").
In the picture below, you can see that I have ran two commands that try to parse a string into JSON. In the first command, the second item in the first array is 03 and outputs a SyntaxError. In the second command, The 03 was changed to 3 and now it parses properly.
I would recommend researching how to add data to the datatable without leading zeros in order for the table to show up properly and then change how the numbers are viewed/displayed
I would also recommend researching json_encode() to echo json from PHP.
I use json_encode() to echo json from PHP all the time to make sure I get the proper data output when making AJAX calls.

how to parseFloat this?

i have this code :
$wage = array();
foreach ($result3 as $row3) {
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
}
if ($userid == 0 ) {
$age= "";
} else {
$age = implode(',', $wage).",";
}
echo json_encode("var2"=>$myvar ,"var3"=>$age)); // i didnt write var2 because is same as var3
the above will outputs something like [4,2.3][5,6],[1.7,5],
and in javascript im receiving this value outputed above via ajax which has name var3.
dataType: 'json' ,
success: function(response){
var age = response['var3'] ;
.....
so the question is how can i parseFloat this variable age ?
EDIT .
if i alert the json like that
alert (response);
i get [object Object] // make attention to small o and big O
EDIT2 .
used consol log
and i get this
{"var2":"[2,5],[3.5,5],[6.5,6.5],[8,7],","var3":"[2,46],[3.5,61],[6.5,70],[8,71],","var4":"[2,32],[3.5,41],[6.5,42],[8,43],","var5":"[46,5],[61,5],[70,6.5],[71,7],"}
this returned values i want to parseFloat them as you see they are like strings between two quotes
This is incorrect:
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
You're building a string, which coincidentally happens to LOOK like a javascript array definition, but it's still just a string. When this gets json_encoded, it'll come out as
"[...,...]"
^-- ^-- string
You need to build NATIVE data structures at all stages while in PHP, e.g.
$wage[] = array(floatval($row3['age']), floatval($row3['point']));
and not this mish-mash of native AND "json-like" strings. json_encode() converts NATIVE datatypes of the equivalent Javascript types. Since your own floatval business is producing a string, you'll get a json-encoded string, not an array.
You are getting this all wrong. You do not need to do this;
foreach ($result3 as $row3) {
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
}
Perhaps what you want is;
foreach ($result3 as $i => $row3) {
$newRow = $row3;
$newRow['age'] = intval($row3['age']);
$newRow['point'] = floatval($row3['point']);
$result3[$i] = $newRow;
}
And then do this;
// Create JSON data, assuming that $result3 is an array
$jsonData = json_encode($result3);
// This will give you a JSON string, output this and finish to ensure it IS the only thing output
echo $jsonData;
die;
Now in your javascript, open the development console in what ever browser your using and use the following code in javascript
console.log(response)
This will output the whole response variable to the console and enable you to debug how to get specific data out of the response var.
Hope that helps.

PHP array to JS array with jQuery and json_encode

I just want to get my PHP array to a JS array, what am I doing wrong here?
PHP:
// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"]
JS:
var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);
Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).
An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.
If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.

Categories