Decoding JSON Data from PHP Page Using Jquery - javascript

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);

Related

Trying to get results of a MySQL query into a JavaScript array

I've got a MySQL database of offices with geo data. I'm trying to get a list of the office cities into a JavaScript array. For now, I just wanted to set up a simple $.ajax() to log the list into the console, but it's returning null. I'm just running my JavaScript function "query()" in console after the page loads.
Here's my JavaScript.
function query() {
$.ajax({
url: "query.php",
method: "POST",
dataType: 'json',
success: function(data) {
let output = JSON.parse(data)
console.log(output)
}
})
}
Here's query.php
<?php
include 'database.php';
$sql="SELECT `Office City` FROM `offices`";
$result = $link->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
Here's database.php. I'm able to write to MySQL using this PHP, so I assume it's correct.
<?php
$hostname = "hostus.mostus.com";
$username = "name";
$password = "pw";
$database = "db";
$link = mysqli_connect($hostname, $username, $password,$database);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" + mysqli_connect_error());
exit();
}
When I run query() in the console, it responds "undefined" then null.
Your sql is invalid.
I would also init the $result_array before. Currently if the result is empty, you are returning null.
<?php
include 'database.php';
$sql="SELECT `Office`, `City` FROM `offices`";
$result = $link->query($sql);
$result_array = [];
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>

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().

How to callback several variables from a page using jquery AJAX

I have spent hours(maybe days) on this problem. I know this question has been asked before but the answers are always so vague for my beginner experience level to understand. I would love some specific and simplified code exampes.
I am submitting an AJAX call to changeDate.php.
index.html
$(document).on("click", "#day-left", function(event){
changeDate = changeDate - 1;
$.ajax({
type: "POST",
url: "changeDate.php",
data: {
amount: changeDate,
loginName: "benjamin_lawson"
},
success: function(data) {
$("#date").html(data);
}
});
});
This page receives the ajax. Using the data it updates SQL and creates 24 variables ($hour1, $hour2, $hour3...) with data.
changeDate.php
<?php
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
$sql = "SELECT `$dateName` FROM `$user` WHERE hour='$x'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
${"hour" . $x} = $row[$dateName];
}
}
}
//this creates 24 variables with all my information I want sent
//through my call back. ($hour1, $hour2, $hour3,...)
How can I pass these variables back to my first page in a callback that keeps the variable name and variable data?
I see a related question to this and they answered with:
RELATED QUESTION AND ANSWER... potential solution
You can return arbitrarily many variables with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in > > your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within > result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
I would really appreciate if someone can show me in code what I need to do to make this work. Thank you so much!
Well every answer is telling to use JSON encode of php. And you required another answers, though theres is already existing a question on that.
Well from php, you can return any data you want. Either you can give a string, or directly HTML or some formatted data like xml or JSON.
Whatever echoed/printed from that request is a response. You can do that request directly from URL or by AJAX. If the request meets the prerequisites, it will show same response.
Now if you just echo any data, there JS no structure and probably you would have to format and parse it to extract meaningful data from it.
But JSON and XML are the know data transport languages. XML is good but needs structuring at server and element based retrieval at client side (there can be many efficient ways which I am unknown to; as I am not a fan of XML). For JSON, you have encode and decode methods at server end and JavaScript is like elder brother to it.
Now how do you form a JSON? You just pass array or object to json_encode and it will return the JSON string. echo that string and your response is ready.
So for I am going to use #Poonam's code; I am making few optimizations also:
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
}
// fill an array from 1 to 24 with steps of 1
// http://php.net/manual/en/function.range.php
$x = range(1, 24, 1);
$sql = "SELECT `$dateName`, hour FROM `$user` WHERE hour IN ('". implode( "', '", $x ) ."')";
$result = $conn->query($sql);
$response_arr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response_arr['hour' . $row->hour] = $row[$dateName];
}
}
echo json_encode($response_arr);
exit(0);
//this creates 24 variables with all my information I want sent
And in the success callback of AJAX, use either JSON.parse() if content type is not mentioned as application/json.
here i use json to encode data .
$.ajax({
type:"POST",
async: false,
url:"finance/getdataq",
dataType: "json",
data: data,
success: function(data){
// you can access your data variables like data['ukeydt'];
$("."+targetval).find('.qrwordfol').html(data['ukeydt']);
$("."+targetval).find('img').attr('src',data['ukeyqr']);
$("."+targetval).show();
return false;
},
error: function (data) {
getd="";
}
});
and in my php code
public function getdataq()
{
$data = array();
$data['ukeydt'] = "this is first";
$data['ukeyqr'] = "this is second";
echo json_encode($data);
exit();
}
You can use an array which will have all values for hours.
In changeDate.php
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
$sql = "SELECT `$dateName` FROM `$user` WHERE hour='$x'";
$result = $conn->query($sql);
$response_arr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response_arr['hour' . $x] = $row[$dateName];
}
}
}
echo json_encode($response_arr);
exit();
//this creates 24 variables with all my information I want sent
//through my call back. ($hour1, $hour2, $hour3,...)
This $response_arr will have $response_arr['hour1']...$response_arr['hour24'] and you can use this array in your success: function(data)
success: function(data) {
console.log(data);
}
You'll get your whole data in 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)

Categories