Modifying a JSON object returned with PDO - javascript

I'm trying to return use a JSON object with handlebars. Making a small todo list to learn how to use it.
My PHP API is as follows :
$query = "SELECT *
FROM table";
try
{
$db = getConnection();
$response = $db->query($query);
$todo = $response->fetchAll(PDO::FETCH_OBJ);
$bdd = null;
echo json_encode($todo);
}
It then returns something like :
[{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]
But I'd actually need it to be like this :
{todos: [{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]}
I tried in my PHP API to add instead of echo json_encode($todo)
echo '{todos: ' . json_encode($todo) . '}';
But it doesn't work. Any ideas ?

Your "todos" property name must be quoted with double-quote characters.
echo '{"todos": ' . json_encode($todo) . '}';
Though JavaScript syntax allows for property names without quotes, strict JSON insists on them.

While Pointy's answer is correct (might want to read about JSON), alternatively you could do this:
echo json_encode(array('todos' => $todo));
PHP associative arrays will be serialized to JSON as objects (json_encode() example in Manual).

Try with :
echo '{ "todos" : ' . json_encode($todo) . '}';

Try this:
echo json_encode(array( 'todos' => $todo ));
Instead of making the JSON yourself, make the structure you want, then have PHP make the JSON for you.

Related

Calling JSON.parse on php returned array, some numbers parsed as INT, others parsed as STRING

Looking for an explanation rather than an answer here :)
I have this php script that is called with jquery's AJAX
$query = 'SELECT MONTH(PRSD#) as "Monat", CAST(AVG(GASVBR) as DECIMAL(10,3)) as "Gas", CAST(AVG(OLVBR) as DECIMAL(10, 3)) as "Öl", CAST(AVG(STROVBR) as DECIMAL(10,3)) as "Strom" FROM swind.gwenergy GROUP BY YEAR(PRSD#), MONTH(PRSD#) ORDER BY MONTH(PRSD#)';
$dbReturn = $database->execute($query, array());
$jsonArray = array();
while ($row = db2_fetch_assoc($dbReturn)) {´
echo json_encode($jsonArray);
}
When I call in the JS side of things:
let parsedData = JSON.parse(jsonData);
I am returned with this:
{Monat: 2, Gas: '13750.607', Öl: '1447.432', Strom: '3901.051'}
How come the Monat value is not in quotes?
I thought that maybe because the $query in the php script was returning DECIMAL(10,3) but when I replace it with FLOOR(... the JSON.parse still wrapped the value in quotes. Is this related to the $query response, or is this a JSON.parse action?
Look forward to hearing other ideas :) Thanks! -Boogabooga
I've faced a similar problem.
You can check the data type on PHP with gettype()
Note that since PHP 5.3.3, there is a flag for auto-convert numerical numbers when using json_encode.
echo json_encode( $jsonArray, JSON_NUMERIC_CHECK );
This should do the work for you.

json_encode only working on some php arrays and not importing the data for others

I am trying to import three arrays from php into js using json_encode
Here is the code:
<?php
$query2 = "SELECT * FROM all_data";
$result2 = $conn->query($query2);
$bu = [];
$rank = [];
$id = [];
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$bu[] = $row2["bu"];
$rank[] = $row2["rank"];
$id[] = $row2["id"];
echo "<tr class='dn' id='u-" . $row2["rank"] . "'>";
echo "<td>" . $row2["rank"] . "</td>";
echo "<td>" . $row2["bu"] . "</td>";
echo "<td>" . $row2["tokens"] . "</td>";
echo "</tr>";
}
}
?>
var users = <?php echo json_encode($bu); ?>;
var ranks = <?php echo json_encode($rank); ?>;
var identifier = <?php echo json_encode($id); ?>;
Problem is, the arrays ranks and identifier are getting imported correctly, but users is not. This script was working the last few times I used it. Recently however, I changed the table all_data, by dropping it and then importing it from csv again. However the charset was utf8 when I imported, so I don't understand what the problem might be here.
Even if I am just doing <?php echo json_encode($bu) ?> it is not working. However <?php print_r($bu) ?> shows me that the array is not actually empty and it actually contains the query results.
json_encode turns the array into a string; if you want to have access to the array again in Javascript, parse the string back to an array again, such as:
var users = JSON.parse('<?php echo json_encode($bu); ?>');
But it's quite bad practice to create JS on the fly like this - if you want the script to have information served from your PHP, either insert the object into a element which gets parsed by the Javascript, or use data- attributes.
As #kip points out in the comments, the most likely cause of the failure is the conversion of a unicode character, or other special characters that is causing the json_encode to fail to encode the array.
Most likely, you will need to use one of the json_encode predefined constants such as #kip recommended:
json_encode($bu, JSON_UNESCAPED_UNICODE);
I would actually take this a step further and use:
json_encode($bu, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR)
Finally, since you know you are getting a json_encode error of some kind, after running your line
var users = < ? php echo json_encode($bu); ?>;
You can add the line:
json_last_error()
This will tell you exactly what the problem is, and should allow you to adjust the parameters of the json_encode to work with your $bu array.

Pass PHP generated JS objects to JS

I generate some JS objects strings in PHP because all of the variables i need are there, instead of passing them to js and generate the object there:
$results[] = "{value:" . $data . ",color:\"rgba($aa,$ab,$ac," . Config::$TRANSPARENCY_B . ")\",highlight:\"rgba($ba,$bb,$bc," . Config::$TRANSPARENCY_B . ")\",label:\"" . $entry->getDate() . "\"}";
Now i want to pass the finished result list of JS object strings to JS in order to display it. The resulting structure should be like: [{object1}, {object2}, ...]
In order to achieve this i use htmlspecialchars(json_encode($result), ENT_QUOTES, "UTF-8")
However this ends up in something of the structure: {"{object1}", "{object2}", ...], which of course won't work. How can i manage to throw away the useless enclosing "? I had a look through json_encode() and htmlspecialchars() but none of the parameters there seems to fit.
Any ideas? Thanks!
EDIT: Turns out i am completely dumb. Of course i should pack up some real objets and not a string representing them.. THANKS!
Why not just create real objects, that way encoding them as JSON is easy
$obj = new stdClass;
$obj->value = $data;
$obj->label = $entry->getDate();
$results[] = $obj;
echo json_encode($results);
Associative arrays would also be outputted as "objects" in JSON, and is probably easier
You would be better off not manually making JSON out of strings and use the json_encode function to do it for you:
$results[] = array(
'value' => $data,
'color' => "rgba($aa,$ab,$ac," . Config::$TRANSPARENCY_B . ")",
'highlight' => "rgba($ba,$bb,$bc," . Config::$TRANSPARENCY_B . ")",
'label' => $entry->getData()
);
echo json_encode($results);

JavaScript - Bring multiple variables from PHP

I have the following PHP code. It creates multiple variables using $a; for example: $numtoken1.
$sql ="SELECT token, dispositivo FROM dispositivos WHERE idcliente=1";
mysql_select_db('localiza');
$retval = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($retval);
while($row = mysql_fetch_array($retval, MYSQL_BOTH))
{
$numtoken['$a']=$row['token'];
$numdispositivo['$a']=$row['dispositivo'];
$a=$a++;
}
Using JavaScript, I want to call all the PHP variables using that code, but it only get the last $a number.
My question is: In a JavaScript loop, how can I dynamically insert the value for $a? Because in the above PHP, I have multiple values for $a.
var accessToken = "<?= $numtoken['$a']; ?>"a;
var deviceID = "<?= $numdispositivo['$a']; ?>";
I suggest JSON:
var accesstoken = JSON.parse("<?= json_encode($numtoken); ?>");
var deviceID = JSON.parse("<?= json_encode($numdispositivo); ?>");
So the first thing I noticed when looking at this is that you are wrapping $a in single quotes (') instead of double quotes (") this means that instead of evaluating $a the key in the array will be the string "$a", so you'll be overwriting the value in each iteration of the while loop. See - http://php.net/manual/en/language.types.string.php#language.types.string.parsing for more info.
That being said the actual answer to your question varies, but the simplest method might be to use the json_encode function to convert your arrays into json objects.
var accessTokenArr = <?php print json_encode($numtoken); ?>
var deviceIdArr = <?php print json_encode($numdispositivo); ?>
Then you can iterate over the values in those arrays and do whatever you want to with the values. Fair warning - you may need to tweak that code a little as I haven't tested it to make sure it plays nicely.

Add a comma to the end of each line using php [duplicate]

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 9 months ago.
I am having a csv file with 1 email id in each line. I want to add comma after each email id. I want to add a comma to the end of each line using php. How can i do this? Is there a particular function for that?
UPDATE
I want this so that I can construct an array out of it in javascript.
I will be loading the csv file using php and then printing it in my js.
Like
var myCars=[<?php print $csv; ?>];
So that I acheive something like this.
var myCars=["Saab#gmail.com","Volvo#gmail.com","BMW#gmail.com"];
Or is there a better way to do this?
$lines = file('file.csv');
foreach ( $lines as & $line ) {
$line .= ',';
}
file_put_contents('file.new.csv', implode(PHP_EOL, $lines));
something like that should do,
cheers
<?php
$lines = file('org.csv');
foreach ( $lines as & $line ) {
$line = trim( $line ) . ',';
}
file_put_contents('new.csv', implode(PHP_EOL, $lines));
Why not use the csv-specific functions?
$old = fopen('file.csv','r');
$new = fopen('new.csv','w+');
while($line = fgetcsv($old))
{
fputcsv($new,$line);
}
fclose($old);
fclose($new);
The above code will write a new csv, line per line, but if you just want to generate a javascript array, why not do this:
$file = fopen ('file.csv','r');
$all = array();
while($line = fgetcsv($file))
{
$all[] = $line[0];//if there is only 1 field/line
$all = array_merge($all,$line);//if multiple
}
fclose($file);
$js_array = '["'.implode('",',$all).'"];';
//or, the way I'd advise against, but good for multi-dimensional, assoc arrays
echo 'var array = JSON.parse("'.json_encode($all).'");';
why not just
$csv = str_replace("\n", ",\n", $csv);
Instead of echoing an entire csv string, you can import the file to an array using the fgetcsv function, then echo it out using json_encode(). That way you're sure to get a valid javascript array. It will also quote and encode any strings for you.
Oh, remember to run the array through some iterator which will run utf8_encode on all strings. If you have invalid utf8 characters, json_encode will barf.
There are plenty of examples on php.net of doing the different parts of this, but I can provide some examples if needed.

Categories