Pass PHP generated JS objects to JS - javascript

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);

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.

Getting data out of this array in JS

Finally i get some output out of PHP instead of just the word "array". This took me a day, AAAAHHHH.
(see here for the solution)
So this is the return value from a XMLHTTP request (to PHP), via a callback in JS. I got it with print_r in PHP.
I post a snippet of the results here.
My new question:
what is this data structure made of?
how to get elements out of this structure, such as CourseID (in JS)?
[0] => Parse\ParseObject Object
(
[serverData:protected] => Array
(
[CourseID] => DEMO2
[EndDate] => DateTime Object
(
[date] => 2017-03-31 10:26:00.000000
[timezone_type] => 2
[timezone] => Z
)
[InfoTitle1] => Welcome
[InfoText1] => Welcome to your course, called "sense & sales".
[Admin] => Remco#Demo1
)
My PHP code is
function getGroups(){
$query = new ParseQuery("CourseInfo");
$query->equalTo("Admin", "Remco#Demo1");
$results = $query->find();
// echo $results // this lead to the string "array"
//print_r($results); // this leads to the complicated array
//echo "<script>\r\n var phpOutput = " . json_encode($results) . ";\r\n console.log(phpOutput);\r\n</script>";
// this leads to [{},{}];
}
What you want is a JavaScript Object, so you need to use JSON.
(JSON means JavaScript Object Notation.)
PHP has a json_encode function, which will do the work for you: (http://php.net/manual/en/function.json-encode.php)
json_encode — Returns the JSON representation of a value
Try this:
PHP:
echo "<script>\r\n var phpOutput = " . json_encode($output) . ";\r\n console.log(phpOutput);\r\n</script>";
Press F12 in your browser to open the browser's Console log window in Developer Tools to see the new JavaScript Object.
You may want to convert your PHP object to JSON first via json_encode().
This will allow you to easily work with it in JavaScript like you normally would with any JavaScript object.
I stopped trying to work with this array/object in JS. But instead i managed it on the PHP side and sent the results to JS.
Now it is all simple. (-;

PHP to Javascript array trouble

so I have this code:
var loc = new Array();
<?php foreach($loc as $key => $val) { ?>
loc.push('<?php print_r($val); ?>');
<?php } ?>
The problem is is that it's only showing one value and not more than one, like it should. This is the php array code:
$loc = array($lat, $long);
Any help is greatly appreciated.
Try this:
var loc = <?php echo json_encode($loc); ?>;
You should not use print_r. Let me quote the documentation:
print_r — Prints human-readable information about a variable
Note the part I emphasised. "human-readable". Just because it looks vaguely like something JavaScript might understand, doesn't mean it is ;) json_encode, on the other hand, is specifically designed to output JSON, which is a subset of the syntax JavaScript accepts for variables.

Modifying a JSON object returned with PDO

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.

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