Unable to load JSON into D3.js from MySQL using PHP - javascript

I am retrieving contents from my database(MYSQL) in PHP. The following is my PHP script:
<?php
$username = "**";
$password = "**";
$host = "**";
$database="**";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT * FROM data1
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
The output is a perfectly formatted JSON Object:
[{"ID":"1","Country":"India","Value1":"100","Value2":"200"},{"ID":"2","Country":"India","Value1":"230","Value2":"800"},{"ID":"3","Country":"USA","Value1":"30","Value2":"300"},{"ID":"4","Country":"Sri Lanka","Value1":"320","Value2":"330"},{"ID":"5","Country":"Sri Lanka","Value1":"120","Value2":"90"},{"ID":"6","Country":"Sri Lanka","Value1":"420","Value2":"890"},{"ID":"7","Country":"China","Value1":"20","Value2":"890"},{"ID":"8","Country":"China","Value1":"430","Value2":"999"},{"ID":"9","Country":"Canada","Value1":"200","Value2":"319"},{"ID":"10","Country":"Canada","Value1":"1000","Value2":"29"}]
I want to use this JSON object as input to my D3.js graph.
When I try to create my D3 chart I get the error in my browsers log:
SyntaxError: Unexpected token < in JSON at position 0(…)
The following is my D3 code where i invoke the PHP file and try to parse the JSON:
d3.json("1.php", function(error, data) {
console.log(error);
//parsing operations
});
Any pointers would be appreciated. Thanks

Related

How to get php echo result in javascript

I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps

How can i choose a particular sheet and display the data in it?

How can I choose a particular sheet and display the data in it. I have used some of the functions in the code which library functions should I add to execute the code?
It is displaying all the Excel file data, but I want specific page or sheet to be displayed.
<?php
require 'Classes/PHPExcel/IOFactory.php';
// Mysql database
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "import_db";
$inputfilename = $_POST['fileToUpload'];
$exceldata = array();
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Read your Excel workbook
try
{
$inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($inputfilename);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputfilename,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
//$sheetNames = $sheet->getSheetNames();
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$count=$objPHPExcel->getSheetCount();
$names = $objPHPExcel->getSheetNames();
echo $count;
echo $names;
//echo $sheetNames;
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
$exceldata[] = $rowData[0];
}
// Print excel data
echo "<table>";
foreach ($exceldata as $index => $excelraw)
{
echo "<tr>";
foreach ($excelraw as $excelcolumn)
{
echo "<td>".$excelcolumn."</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Change below code in try and it will work for you.
try
{
$sheetname = 'Data Sheet #2'; // Sheet name which you want to load
$objReader = PHPExcel_IOFactory::createReader($inputfiletype); // Create a new Reader of the type defined in $inputfiletype
$objReader->setLoadSheetsOnly($sheetname); // Advise the Reader of which WorkSheets we want to load
$objPHPExcel = $objReader->load($inputfilename); //Load $inputfilenameto a PHPExcel Object
}

PHP Javascript T_VAR [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I'm attempting to extract lat/long points from MySQL to eventually plot them in Leaflet using Javascript. I ran the following PHP code (planelatlong.php) and got an error:
Parse error: syntax error, unexpected 'var' (T_VAR) on line 24.
I looked at similar errors on Stack Overflow for T_VAR, but couldn't find a clear solution for my issue.
Code:
<?php
$username = "stackoverflow";
$password = "thanksstackoverflow";
$host = "localhost";
$database="homedb";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
echo "Connected successfully";
$myquery = "SELECT 'lat', 'lon' FROM 'test01';
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
$data = array();
echo "var planelatlong = [";
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
echo "[",$data[$x]['lat'],",",$data[$x]['lon'],"]";
if ($x <= (mysql_num_rows($query)-2) ) {
echo ",";
}
}
echo "];";
mysql_close($server);
?>
I think you forgot to end double quote at line 13. Use below line
$myquery = "SELECT 'lat', 'lon' FROM 'test01'";

I have a php file which gives JSON output and want to use that JSON in D3

I have a php file names test.php which gives me a JSON output which is a valid output as I have validated in http://jsonlint.com/ .I want to use that JSON directly in my .html code which used D3.
test.php
<?php
$user = "root";
$password = "";
$database = "scheduler";
$con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect");
$query = "SELECT semone.userid AS id, semone.semester AS semester, semone.cname AS name, courses.credit AS value, courses.progskill AS skill
FROM semone
INNER JOIN courses
ON semone.cname = courses.coname" ;
$result = mysqli_query($con,$query)or die ("Unable to connect");
$lastId = null;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['xyz'] = array(
'name'=> $row['name'],
'value'=> $row['value']
);
$info[$row['semester']]['semester'] = $row['semester'];
$info[$row['semester']]['children'][]= $row['xyz'];
$lastId = $row['id'];
}
// do not call json_encode on each iteration of the loop
$data = json_encode(array('id' => $row['id'], 'children' => array_values($info)));
// echo $data;
?>
The html code where I am trying to use the JSON created from test.php in D3.
tree.html
var canvas = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height + padding);
var data;
d3.json("test3.php", function (error,json) {
if(error) return console.warn(error);
data = json;
console.log(data);
var treemap = d3.layout.treemap()
.size([550,550])
.nodes(data);
var cells = canvas.selectAll(".cell")
.data(treemap)
.enter()
.append("g")
.attr("class","cell")
It is not showing anything as if it is not able to access that JSON file. However When I am using the same JSON through some JSON file saved in the folder, it is working fine. So there is some problem in connection of this html and php file.
Uncomment the echo $data . It should work fine.

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.

Categories

Resources