cannot receive json in js ajax request from php file - javascript

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.

Related

Decoding JSON Data from PHP Page Using Jquery

I want to take data from database and save it in an array.
Like this
 var locations = [ ['Current', 18.53515053, 73.87944794, 2],
['VimanNagar', 18.5670762, 73.9084194, 1]
];
First of all I have created a php page
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "citytrans";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM driver_location";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode($row);
}
} else {
echo "0 results";
}
$conn->close();
?>
which gives me below result
{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"}{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}
Now I want to convert this into an array using Jquery (I want to decode it ), I just want drivers_lat and drivers_lng value from my jSON data fetched form the database show above.
I am using below code to parse the data form json
jQuery.ajax({
url: baseurl + "getdriverlocation.php",
type: "JSON",
async: false,
success: function(data){
var myArray = JSON.parse(data);
console.log(myArray.driver_lat)
}
});
but it is giving me error (shown below)
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 92 of the JSON data
I just want the two values from json data and save it in an array variable
Please help
Use this one..
jQuery.ajax({
url: baseurl + "getdriverlocation.php",
type: "JSON",
async: false,
success: function(data){
var myArray = jQuery.parseJSON(data);// instead of JSON.parse(data)
jQuery(myArray).each(function( index, element ) {
console.log(element.driver_lat)
});
}
});
In your php you should do :
if ($result->num_rows > 0) {
// output data of each row <- no, build your data, then make only 1 output
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
}
Then in your jQuery, parse the whole json-decoded array...
Your json data is invalid.
You must put comma bettween two JSON Objects
Your respons must be
{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"},
{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}
As i identified your Response JSON format is invalid, response JSON format should like this in order to parse into JSON via JSON.parse()
[{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"},
{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}]
Try this
$arrTmp = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$arrTmp[] = $row;
}
}
echo json_encode($arrTmp);
And maybe the jQuery tools bellow for old browsers
$.parseJSON(data);

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)

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

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'
";

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/

JSON Encode Failure

PHP PAGE:
<?php
include "linkpassword.inc";
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($showresult);
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
addVote();
showVotes();
?>
I am trying to get the output of the array to load into a JavaScript page where I can break up the array into seperate divs that have IDs assigned to them. Here is what I tried
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
Where am I going wrong??
From what you've posted in comments, what you have is an array of objects.. not html, as your function seems to indicate. Depending on what you want done, the answer would be either of the following, to access that object's properties:
showVotes[0].votes
Or
showVotes[0]['votes']
Eg:
$('#rvotes').html(showVotes[0].votes);
Or etc.
Second attempt:
Firstly, change your current 'showVotes' function to this:
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_assoc($showresult)) {
$response[] = $row;
}
return json_encode($response);
}
Secondly, remove your 'connected successfully' text from the page, as well as any other text generated by anything else(aka, the other function which returns a result pointer). I may be wrong, but it would seem to me that the generation of this other text is causing the returned json to be interpreted as malformed.
Quick explanation on PDO:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>";
die();
}
Connecting to the database.. This is how I've learned to do it, though I've been warned(and downvoted) to not check for errors this way, though it was never explained why.
Database interaction:
$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color");
$stmt->bindParam(":color",$_POST['color']);
$stmt->execute();
Result use:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row;
}
And so on and so forth. PDO escapes the values for you, so you don't have to worry about injection attacks.

Categories