d3.js How to pass parameter to php for query condition - javascript

I attempt to combine d3, mysql php Tutorial.
I want to use mysql to store data, and use d3 table to display the result.
Following the tutorial I successfully connected the sql, and display it.
However, in my example, the where condition of sql in queryData.php is hard encoded.
As show below: WHERE pathwayID='1643685' && symbol='VIF'
I need to pass the parameter '1643685' and 'VIF' from d3 file to php file, how should I do?
And how should I modify queryData.php, thanks.
d3 file
d3.json("queryData.php", function(error, jsonData) {
....
});
queryData.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
// load in mysql server configuration (connection string, user/pw, etc)
include 'mysqlConfig.php';
// connect to the database
#mysql_select_db($database) or die( "Unable to select database");
//Query
$myquery = "
SELECT `pathwayID`, `proteinID`, `uniprotID`, `symbol`, `displaySymbol`, `reactomeID`, `cellularLocation` FROM `protein` WHERE pathwayID='1643685' && symbol='VIF'
";
$result = mysql_query($myquery);
if ( ! $result ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($result); $x++) {
$data[] = mysql_fetch_assoc($result);
}
echo json_encode($data);
mysql_close();
?>
mysqlConfig.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$username="root"; //replace with your mySql username
$password=""; //replace with your mySql password
$database="pathway"; //replace with your mySql database name
$host="localhost"; //replace with the name of the machine your mySql runs on
$connection=mysql_connect($host,$username,$password);
?>

Finally, I solved this by using ajax to post parameter.
$.ajax({
url: "./php/querybyPathwayId.php",
type: "GET",
data: {
pathwaydbId: dbId
},
dataType: "json",
success: function (jsonData) {
operation(jsonData);
},
error: function () {
}
});
and modified the querycentance
$pathwayId = $_GET["pathwaydbId"];
$myquery = "
SELECT `pathwayID`, `proteinID`, `uniprotID`, `symbol`, `displaySymbol`,
`reactomeID`, `cellularLocation` FROM `protein` WHERE pathwayID='$pathwayId'
";

Related

cannot receive json in js ajax request from php file

onclick onto a button the js starts an ajax request to the php file. The php file then gets all entries of one table of a database with php-loop. adding them to an array then the php file parse it to a JSON and echos it back to the ajax request. on success the ajax request should output an alert but neither do i get an error nor a alert.
After adding some changes according to the comments. it is now showing the error message 2 error messages randomly:
Fehler: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
Fehler: {"readyState":4,"responseText":"<br />\n<b>Fatal error</b>: Uncaught Error: Cannot use object of type mysqli_result as array in C:\\xampp\\htdocs\\integration\\get.php:32\nStack trace:\n#0 C:\\xampp\\htdocs\\integration\\get.php(13): getLevel1()\n#1 {main}\n thrown in <b>C:\\xampp\\htdocs\\integration\\get.php</b> on line <b>32</b><br />\n","status":200,"statusText":"OK"}
php request (mysqli attributes are left out on purpose):
$func = $_POST['func'];
if ($func == "getLevel1"){
getLevel1();
}
$result = array();
function getLevel1(){
// Create connection
$conn = new mysqli(servername, username, password, dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM capability_level1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
}
echo json_encode($result);
} else {
echo json_encode("0 results");
}
$conn->close();
}
js ajax call:
async function getLevel1() {
return $.ajax({
type: "POST",
dataType: "json",
url: "get.php",
data: {
func: "getLevel1"
},
success: function(data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function(data) {
alert("Fehler: "+ JSON.stringify(data));
}
});
}
You need to put the json encoding when you have a complete array to be encoded: after the while:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
}
echo json_encode($result);
} else {
Also note that you probably have to change your data type to Json (and send a json to php) to be able to return it. Actually your Ajax is waiting for text to be returned (based on the data type)
For your further error: it is related to the point that you are fetching the rows from mysql using the wrong function. See this question for more details on how to fix it.

PHP array to seperate JavaScript file via AJAX

I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...
You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().

Pass a variabile from php to js via JSON

At the lessons i learn how to pass result from a sql request to js via JSON/AJAX. I need the value of the row from this request in my js but it doesnt work. Via console i have an error: Uncaught SyntaxError: Unexpected token <
part of PHP:
<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
exit(); //do nothing else
}
else {
# extract results mysqli_result::fetch_array
$query = " SELECT * FROM course WHERE course_category='$id'";
//query execution
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
$myArray = array();//create an array
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = array_map('utf8_encode', $row);
}
$response = array();
$response['rows'] = $row;
$response['query'] = $myArray;
echo json_encode($response);
}
//free result
$a=num_rows;
$result,$a->close();
//close connection
$mysqli->close();
}
?>
first part of Script:
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
data: {id: i},
success: function(response) {
console.log(JSON.parse(response));
var course=JSON.parse(response.query);
var row=JSON.parse(response.rows);
Seem you use JSON.parse in wrong way.
The JSON.parse must be done one time only. The result of JSON.parse is store in course the the access to the data is due by response.query or respons.row .. and so on and not by JSON.parse(respose.query)

fetch rows from mysql using Ajax

I am trying to retrieve a row from mysql db using ajax, code bellow:
jQuery.ajax({
type: 'POST',
url: 'Connection.php',
dataType: 'text',
data: {'query_id' : query_id},
success: function(response){
data = response;
alert(data['username']); //print undefined!!!
},
error: function(xhr, ajaxOptions, thrownError){
alert("thrownError");
}
});
Here is my mysql php code:
<?php
$con = mysql_connect('****','****','****');
mysql_select_db("eBay",$con);
$username = $_SESSION['username'];
$query_id = $_POST['query_id'];
$myquery = "SELECT * FROM `Output` WHERE `username` =" '$username';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
}
$data = mysql_fetch_array($query);
echo ($data);
mysql_close($server);
?>
In the response I get, I have undefined array cell. Any idea?
to return just the username from php:
$data = mysql_fetch_assoc($query)['username'];
in your javascript you should be able to do alert(data) instead of searching for the username tuple in an array.
Ideally you should return your data back in json instead of text that way it can remain structured and easier to access in javascript. You will need to change your ajax option to dataType: 'json'
and the PHP code to :
$data = json_encode(mysql_fetch_assoc($query));
You are getting array in $data variable so you should use json_encode function to get all values from resulting row like this-
$myquery = "SELECT * FROM `Output` WHERE `username` ='".$username."'";
foreach ($myquery as $test)
{
$field1_value =$test->name_of_field1_in_db;
$field2_value =$test->name_of_field2_in_db;
$field3_value =$test->name_of_field3_in_db;
}
$all_values_in_array=array('field1'=>$field1_value,'field2'=>$field2_value,'field3'=>$field3_value,);
echo json_encode(echo json_encode($arr_provider);
and get all value on ajax suucess function like this--
success: function(response){
var pro = jQuery.parseJSON(response);
var field1_val=pro.field1; //var field1 contain value of field1 in db
var field2_val=pro.field2;
var field3_val=pro.field3;
},
hope it will help you.
Best of Luck

How to load data from sql through ajax using php variable?

My HTML/PHP code:
<br/><br/><div id="dialog-modal"></div><br/><br/>
<?php foreach (range(0, 29) as $rs) { ?>
<a data-toggle="modal" href="#" data-href="rsc1<?php echo $rs;?>" class="link">pvz - rsc1<?php echo $rs;?></a><br/>
<?php } ?>
My JavaScript code:
$('.link').on('click',function(e){
var linkValue = $(this).attr('data-href');
$.ajax({
cache: false,
type: 'GET',
//url: 'details.php',
//data: 'i=' + linkValue,
success: function(data) {
$('.ui-dialog-title').html(linkValue)
$('#dialog-modal').html(linkValue).dialog();
}
});
e.preventDefault();
});
The details.php code:
$i = $_GET['i'];
echo $i;
This script opens only new dialog with my sent data from url data-href. All I want to do is to take some data from sql db into that dialog window by variable $i…
I think you want to know how to get data from sql database and show it in your ajax response.
If so then try something like this:
details.php code:
$i = $_GET['i'];//getting your data
$link = mysqli_connect("localhost", "my_user", "my_password", "db name");//set your correct database connection string
//check if connection errors
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//make a query with valid table name
$result = mysqli_query($link, "SELECT * from your_table ");
if($result->num_rows){ //check if any data found
while ($row = mysql_fetch_assoc($query)) {
echo $row['id'];// echo this data
}
}
else{
echo "no data found!";//echo no data found
}
mysqli_close($link); // close mysql connection
In this php page what ever i have echoed it will send as ajax response in your success call back's data. that will display in your modal. I just tried to give you a basic idea. I think it will help you.
Some good resource links: http://www.phptutorialforbeginners.com/2013/01/jquery-ajax-tutorial-and-example-of.html
http://www.cleverweb.nl/php/jquery-ajax-call-tutorial/

Categories