Alternative for JSON_ENCODE to be called in d3js graph - javascript

I need to plot d3.js histogram and i have troube in plotting the data from database.
php code is as follows.
<?php
// Create connection
$con=mysqli_connect("localhost","","","a");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `b` FROM `h` LIMIT 1");
while($row = mysqli_fetch_array($result))
{
$s1[] = $row['b'];
$length=count($s1);
for($i=0;$i<$length;$i++)
{
$a = array(preg_replace("([c]+)", "",$s1[$i] ));
$b=(str_replace(array( '(', ')') , '', $a));
print_r($b);
$p=implode(" ",$b);
print_r($p);
$co=array_map('strval', explode(',', $p));
echo '</br>'."my array";
print_r($co);
}
}
$result1 = mysqli_query($con,"SELECT `a` FROM `h` LIMIT 1");
while($row1 = mysqli_fetch_array($result1))
{
$s2[] = $row1['a'];
$length1=count($s2);
for($j=0;$j<$length1;$j++)
{
$a1 = array(preg_replace("([c]+)", "",$s2[$j] ));
$b1=(str_replace(array( '(', ')') , '', $a1));
print_r($b1);
$p1=implode(" ",$b1);
print_r($p1);
$co1=array_map('strval', explode(',', $p1));
echo '</br>'."my array2..........";
print_r($co1);
}
}
$map=array_map(null,$co1,$co);
echo "<br>";
echo JSON_ENCODE($map);
echo "<br>";
$object = new stdClass();
$length5=count($s2);
// echo "lennnnnnnnn".$length5;
for($l=0;$l<7;$l++) {
foreach ($map[$l] as $key => $value)
{
if($key == 0)
$object -> a = $value;
else if($key == 1)
$object -> b = $value;
}
$newArr[$l] = JSON_ENCODE($object);
}
print_r($newArr);
mysqli_close($con);
?>
printing array using,
print_r($newArr);
displays the following,
Array ( [0] => {"a":"26.5","b":"80"} [1] => {"a":" 27","b":" 222"} [2] => {"a":" 27.5","b":" 303"} [3] => {"a":" 28","b":" 408"} [4] => {"a":" 28.5","b":" 276"} [5] => {"a":" 29","b":" 151"} [6] => {"a":" 29.5","b":null} )
in d3js code,
var bins = <?php echo JSON_ENCODE($newArr) ; ?>;
bins.forEach(function(bin) {
bin.a = +bin.a;
bin.b = +bin.b;
});
displays the following,
["{\"a\":80,\"b\":26.5}","{\"a\":222,\"b\":27}"," {\"a\":303,\"b\":27.5}","{\"a\":408,\"b\":28}","{\"a\":276,\"b\":28.5}","{\"a\":151,\"b\":29}"," {\"a\":null,\"b\":29.5}"]
I need to call this output in my d3.js code using echo json_encode. When using this, the data creates forward slashes "\" with the numbers and so the numbers are not read as input for the graph. Is there any way to remove the slashes or to take the data with any other alternate code or function?
thanks in advance.

You didn't provide a complete example, but it looks like you're double json_encodeing. You json_encode array of already json_encoded values.

Related

I am exporting data from table convert to CSV, to JavaScript variable. . But getting Error "fputcsv() expects parameter 2 to be array" . How to do it?

This is my PHP code
<?php
require_once 'd:\xampp\htdocs\bpr\pdo_db.php';
$sql = "Select ID,FULL_NAMe,AGE from TRIAL";
$csv = get_csv_string($dbh, $sql);
echo "<script> var_csv='" . $csv . "' </script>";
function get_csv_string($dbh, $sql)
{
try
{
$result = $dbh->query($sql);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == null) {
return "No Data";
}
$f = fopen('php://memory', 'r+');
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
//second query gets the data
$data = $dbh->query($sql);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $row) {
if (fputcsv($f, $row) === false) {
return false;
}
} // end record loop
rewind($f);
$csv = stream_get_contents($f);
return rtrim($csv);
} catch (PDOExepction $e) {
return $e->getMessage();
}
return $csv;
}
I am getting following error!
Instead of fputcsv(), I made my own code. But issue if found when I save the CSV to a javascript variable. Is there any other way to convert the data to CSV and pass it on to javascript?
I will convert this csv to JSON at Client side using javascript
You're trying to output a header row to CSV with the field names.
This code fails because you're looping through the $row array and attempting to write one field header at a time.
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
What you want is an array with the field names in it. You can use array_keys() for that, so your code becomes
if (fputcsv($f, array_keys($row)) === false) return false;
No loop required.

How to replace the variable from controller to into a (.php) file

I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);

How to convert a JSON to an array which can be used to bind values in a dropdown list?

I have an application where I can generate JSON, which in turn I use as input to GoogleCharts API to draw different visualizations. The pages of this web application are in HTML.
Suppose I have a JSON which has a list of departments of a hospital, like: [{"v":"General Medicine"},{"v":"Laboratory"}]
How do I use Javascript to convert this to an array which in turn can be used as option values of a drop down list?
I am using the following code to generate JSON:
<?php
$serverName = "forestroot"; //serverName\instanceName
$connectionInfo = array( "Database"=>"****", "UID"=>"****", "PWD"=>"****");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT distinct([DEPT_NAME]) as dept FROM [Pristine11Dec15].[dbo]. [PACKAGE_REVN]";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query( $conn, $sql, $params, $options);
if (sqlsrv_num_rows( $result ) > 0) {
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$array[] = array('v'=>$row["dept"]);
}
}
echo json_encode($array);
sqlsrv_close( $conn);
?>
The output is [{"v":"General Medicine"},{"v":"Laboratory"}]
When I use JSON.parse in my code I am getting the options as [object Object] in the drop down list. Where am I going wrong?
var json = '[{"v":"General Medicine"},{"v":"Laboratory"}]';
Parse the data and use map to return an array of v values:
var list = JSON.parse(json).map(function (el) {
return el.v;
}); // [ "General Medicine", "Laboratory" ]
DEMO
You could extend this however to build up the HTML for the select:
var templ = '<option value="#{el}">#{el}</option>';
var options = JSON.parse(json).map(function (el) {
return templ.replace('#{el}', el.v, 'g');
}).join('');
var select = '<select>' + options + '</select>';
document.getElementById('menu').insertAdjacentHTML('beforeend', select);
DEMO

Passing a 2D Array from PHP to Javascript

I'm a beginner in using PHP and Javascript, and I don't have any idea on how to store the data that I've gathered from MySQL which I placed in a multidimensional array in PHP to a 2D array in Javascript. Here's my working code in PHP:
<?php
function connecToDatabase(){
$host = "localhost";
$username = "root";
$password = "p#ssword";
$database = "flood_reports";
mysql_connect("$host", "$username", "$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
}
function retrieveData(){
connecToDatabase();
$data = mysql_query('SELECT * FROM entries') or die(mysql_error());
$entries = array();
$index = 0;
while($info = mysql_fetch_array( $data ))
{
$entries[$index] = array('entry_id' => $info['entry_id'],
'location' => $info['location'],
'image_dir' => $info['image_dir'],
'longitude' => $info['longitude'],
'latitude' => $info['latitude'],
'level' => $info['level']);
$index++;
}
$json = json_encode($entries);
echo $json;
mysql_close();
}
retrieveData();
?>
on the end of your script add the following
<script type="text/javascript">
var jsvar = <?php echo $phpvar;?>
</script>
Replace
echo $json;
with
echo 'var fromPhp = ' . $json . ';';
You just need to put the data into a variable. This will make it available as fromPhp on the browser side.

Display All Data with PHP AJAX JSON using JQUERY

filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);

Categories

Resources