getting JSON into d3.js file - javascript

I have a chart created using d3.js where if you hover over the months,the weekly scores are found.
Fiddle link to the chart I am talking about here : https://jsfiddle.net/qp7L1hob/1/
I also have a table in my DB where I maintain the record of the scores of the Employees every week.What you see here is only for four weeks - (week1 to week4) but in my DB I have record for all the weeks of the months.This is just for reference .
Table pointsScored :
After the user logs in,I want to display only that person's relevant scores.Lets say if Rob logs in,his score for week1 is 47 , week2 is 44, week3 is 44 and week4 is 43.
Issue : I am Using php to extract json from SQL server . Below PHP file does that.
The problem is that how do I get the JSON into the d3.js file, i.e the above fiddle.
please help.
json file (lets name it as data.php) :I understand that I need to include this data.php in the above d3.js file.But not sure how.
<?php
session_start();
$servername="xxxxxxx";
$connectioninfo=array('Database'=>'xxxxxx');
$conn=sqlsrv_connect($servername,$connectioninfo);
if($conn)
{
echo 'connection established';
}
else
{
echo 'connection failure';
die(print_r(sqlsrv_errors(),TRUE));
}
$q1="SELECT WeekNumber,pointsRewarded,EmployeeID FROM pointsBadgeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt=sqlsrv_query($conn,$q1);
if($stmt==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
echo json_encode($result); //You will get the encoded array variable
?>

Let me give you the direction to understand, you can use AJAX to call your php file and get data
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var dataObj = JSON.parse(response.responseText); // parse data into JSON object
chartDrawFunction(dataObj); // call draw here, to load chart only when you have data
}
};
xhttp.open("GET", "data-url-to-be-passed", true); // pass the URL here
xhttp.send();
Update
As i understood the question other way if PHP file was separate from the view. In view you can echo the data in a JavaScript variable like
var data = <?php echo data; ?>;

Related

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

How to retrieve Data from Php while in Node.js

I just wanted to retrieve some PHP/Mysql stuff at the beginning of my app (authentication and x and y data) from the users which I later plan to emit to the app.js (one time at the beginning and once the user disconnects update x - y values).
So basically I have set up Nodes.js and understood that some stuff is not possible like before (e.g with plain php)
Where I already have a problem is the AJAX php request in the index.html of my nodes Server
Schema:
app.js: pull Data from the /Client/index.html (I think need to do it via sockets)
index.html: get or post data via Ajax to a php file and get the values of the database back to the index.html(JavaScript)
then send that data via sockets to the app.js
php: select mysql database
retrieve values from mysql
parse them via Json and make them available in the index.html file Nodes.js (Client)
Maybe somebody of you have a solution
Nodes.js /Client/index.html:
function checkuser(username, password) {
var myObj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myObj = xhttp.responseText;
var i = 0;
while (i <= myObj.length) {
//console.log("ASQL found and Auth Username:"+ myObj[i].username) ;
console.log(myObj.username);
i++;
}
}
};
xhttp.open("GET", "/client/is_user.php?username333=" + username + "&password333=" + password, true);
xhttp.send();
}
is_user.php:
<?php
require('config_sql.php');
$email = stripslashes($_GET['username333']);
$email = mysqli_real_escape_string($con,$email);
$password369 = stripslashes($_GET['password333']);
$password369 = mysqli_real_escape_string($con,$password369);
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password369)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$response = array();
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
echo $jsonData;
mysqli_close($con);
?>
atm is not retrieving the username form the created json on the php side.
If I console.log(myObj); it's showing the me complete php.file data as plain text if I want to retrieve the username from MySql its saying undefined.
Is the php Interpreter actually working when I post/get via Ajax in a Node.js environment?
Normally when I was programming with pure php all the request worked well.
Thank you in advance.
Check you code for recieving result from query:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
Should be so:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row_user;
}
$jsonData = json_encode($response);

AJAX call unable to fetch data from PHP, shows undefined data

I am new to web development and this is my first question here so please don't mind my vagueness, if any.
Now, I am facing facing problem with my javascript file which is supposed to draw a line chart.
Through an ajax call I am unable to fetch data from a php file which gets some variable from a html form. The problem is that I am not getting anything when I load my test.html (which includes the necessary file) not even in console.
Relevant part of my js file is here (graph.js):
$(document).ready(function(){
$.ajax({
url : "http://localhost/series/data.php",
type : "GET",
dataType: "json",
success : function(data){
console.log(data);
var time = [];
var sensor1 = [];
var sensor2 = [];
var sensor3 = [];
for(var i in data) {
time.push("time " + data[i].time);
sensor1.push(data[i].sensor1);
sensor2.push(data[i].sensor2);
sensor3.push(data[i].sensor3);
}...
And this is my PHP file(data.php):
<?php
header('Content-Type: application/json');
//connects to database
include '2connect.php';
//gets a date of which sensor data is to be displayed
if(isset($_GET['dateselector'])&&!empty($_GET['dateselector'])){
$date=$_GET['dateselector'];
//echo "$date";
$query1= "SELECT `time`,`sensor1`,`sensor2`,`sensor3` FROM `$date`";
if($result = mysqli_query($con,$query1)){
$data=array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
}
$result->close();
$con->close();
print json_encode($data);
}else {
echo"<br> failed <br>";
}
}else {
echo "You didn't select a date \n";
}
?>
Whenever I remove the isset check from my php code and give $date a value the code runs perfectly. Is it so that ajax doesn't fetches data from a php file which gets data (form data) from another file?
EDIT: The process is: User chooses a date from the calender (index.html) that date is sent to a php file (data.php) which displays the result in json format. Then in another browser I open a html file(test.html) which includes graph.js and graph.js should fetch data from data.php.

bring data from a JSON and show in a popup

I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!

I am unable to pass on the value to a PHP script from a javascript using JSON

What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];

Categories

Resources