Using PHP to stringify JSON, but having syntax errors - javascript

I'm utilizing PHP to stringify input from my form to a JSON. It's currently formatting it like this
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf#asdf","age":"21","gender":"Male","submit":"Submit"},
But it should look more like this, right?
[
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf#asdf","age":"21","gender":"Male","submit":"Submit"}
]
Here is my current php. What should I do to make it stringify correctly?
<?php
if (isset($_GET['name'])){
$json_data = json_encode($_GET);
// var_dump($json_data);
$file = file_put_contents('data.json', $json_data."," , FILE_APPEND |
LOCK_EX);
?>
<script type="text/javascript">
ChangeName(<?php echo("'".$_GET['name']."'") ?>);
</script>
<?php } ?>

The only way to do this is to read data from the file first, decode it, append the new array to that data and encode it again to json and put it in the file, sort of like this:
<?php
if (isset($_GET['name']))
{
$data = json_decode(file_get_contents('data.json'), true);
$data[] = $_GET;
$json_data = json_encode($data);
$file = file_put_contents('data.json', $json_data);
}

Related

'unexpected token: identifier error' - assigning php json array type variable value to a javascript function from php code

I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>

Receiving and sending back json data in PHP

I am sending data from services.js coming in as a json encoded string in the following format to myPhp.php:
{"Name":"alpha"}
I want to gather this data and send back to the services.js as it came back in json form adding beta to the string as in:
{"Name":"alpha beta"}
myPhp.php
<?php
$a = $_POST[data];
$b = json_decode($a);
$c = $b.Name + "beta";
echo ($c);
?>
The "." notation is not used in PHP to access / set properties - more like Javascript and you need to have quotes around the $_POST variable ~ unless data is defined as a constant. I think you could try something like this though.
<?php
$b = json_decode( $_POST['data'],true );
$b['name'].='beta';
echo json_encode($b);
?>
<?php
$a = $_POST[data];
$b = json_decode($a);
$c = $b['Name'] . " beta";
header('Content-Type: application/json');
echo json_encode($c);
?>

csv to JSON not working

I have a csv file that I want transfer into JSON but it doesn't work the way I was hoping
PHP
$file = $_FILES['csv']['tmp_name'];
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(";", $csv));
echo "<script type='text/javascript'>alert('OK!');</script>";
javascript
var myJsarray = <?= json_encode($array); ?>;
alert(myJsarray[0][0]);
my csv looks something like this
aaa;46
bbb;23
ccc;51
ddd;23
and my output looks like this
[["aaa"],["46\r\nbbb"],["23\r\nccc"],["51\r\nddd"],["23"]];
and I was hoping to get
[["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]]
my idea was to put "$csv=explode("\n", $csv)" under "$csv= file_get_contents($file); "
But it gave me error that "$csv is not a string.
http://jdl-enterprises.co.uk/sof/25763045.php
If it's something like this that you want:
$csv= file_get_contents($file);
$array = explode("\r\n", $csv); // Update this to \n if need be or however you csv saves it
for($i=0;$i<count($array);$i++){
$array[$i] = explode(';', $array[$i]);
}
This will produce:
[["aaa","46"],["bbb","23"],["ccc","51"],["ddd","23"]]
And if you want it like your example, add into the code:
$array2 = array();
foreach($array as $ar) {
foreach($ar as $a) {
$array2[] = $a;
}
}
This will produce:
["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]
Obviously there is a set of [ ] missing around the whole code, but you could stuff it all inside another array, or just add them manually.
Your "CSV" is in an incorrect format:
aaa;46 bbb;23 ccc;51 ddd;23
Change it to:
aaa,46 bbb,23 ccc,51 ddd,23
You do know there is a function just for reading CSV in PHP? It's called fgetcsv()
$data = array();
$fh = fopen('file.csv', 'r');
while (($line = fgetcsv($fh, 0, ';')) !== false) {
$data[] = $line;
}
fclose($fh);
echo json_encode($data);

trying to use simplexml to access the name from ean hotel list

I am trying to use simplexml to access the hotelname from an api, showing a hotel list.
I have used this code so far. It seems right to me, but I still can't get it to work.
<?php
$xml_file = 'http://dev.api.ean.com/ean-services/rs/hotel/v3/list?minorRev=99&apiKey=ycdydfqdz4w5huxv4psfxs8h&cid=55505&locale=en_US&currencyCode=USD&supplierCacheTolerance=MED_ENHANCED&countryCode=US&city=Dallas&stateProvinceCode=TX&searchRadius=50&numberOfResults=20&arrivalDate=08/31/2014&departureDate=09/15/2014&minRate=100&maxRate=1000&room1=1&numberOfAdults=2';
$xml = simplexml_load_file($xml_file);
$response = $xml->HotelListResponse->HotelList->HotelSummary;
foreach($response as $val){
echo $val->name;
}
?>
This should be your new code:
<?php
$xml_file = 'http://dev.api.ean.com/ean-services/rs/hotel/v3/list?minorRev=99&apiKey=ycdydfqdz4w5huxv4psfxs8h&cid=55505&locale=en_US&currencyCode=USD&supplierCacheTolerance=MED_ENHANCED&countryCode=US&city=Dallas&stateProvinceCode=TX&searchRadius=50&numberOfResults=20&arrivalDate=08/31/2014&departureDate=09/15/2014&minRate=100&maxRate=1000&room1=1&numberOfAdults=2';
$content = file_get_contents($xml_file);
$xml = json_decode($content);
//$xml = simplexml_load_file($xml_file);
$response = $xml->HotelListResponse->HotelList->HotelSummary;
foreach($response as $val){
echo $val->name;
}
?>
Somehow the file request answers with a JSON file. Just parse it this way.

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories