convert data from mysql db to table using an json/php api - php

I'm trying to make my own api using a JSON and PHP script, which is successfully working (api.mystem.tk/product), however I want to convert that data to an html table with the columns: id, name and date.
My question, how? I've got my code included and you can watch the JSON output in the console of api.mystem.tk/product. I've deleted all the private details in the scripts and replaced them with #______.
api.php:
<?php
$connect = mysqli_connect('#host', '#user', '#password', '#db');
if(!isset($_GET['function'])) {
die('Some error occurred!');
}
function GetProducts($db) {
$sql = mysqli_query($db, 'SELECT * FROM php_test ORDER BY Id ASC LIMIT
0, 10');
$data = array();
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_array($sql)) {
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
}
}
$data = json_encode($data);
echo $_GET['jsonCallback'].'('.$data.')';
}
if (function_exists($_GET['function'])) {
$_GET['function']($connect);
}
echo $data;
?>
function.js:
$(function(){
var functionName = 'GetProducts';
function LoadData() {
$.getJSON("http://api.mystem.tk/product/api.php?
function="+functionName+"&jsonCallback=?", function(data) {
var all_data = [];
$.each(data, function(k, name){
var array_data = '<div class="names">'+name+'</div>';
all_data.push(array_data);
});
$('#data').append(all_data);
console.log(data);
});
}
LoadData();
});
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title> API TEST </title>
<meta name="viewport" content="width=device-width,initial-
scale=1,maximum-scale=1,user-scalable=0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div id="data"></div>
<script type="text/javascript" src="function.js"></script>
</body>
</html>

so i've tried using $.parseJSON instead of $getJSON, but without succes
console:
Uncaught SyntaxError: Unexpected token <
at m (jquery-3.3.1.min.js:2)
at Function.globalEval (jquery-3.3.1.min.js:2)
at text script (jquery-3.3.1.min.js:2)
at Ut (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
and i've changed this:
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
to this:
$data[] = array(
'id' => $row["Id"],
'name'=> $row["Name"],
'date'=> $row["Date"]
)
to be a little bit more specified...

You'll need to parse JSON data in your function.js using jQuery.parseJSON() jQuery function.
You can read brief documentation from: jQuery.parseJSON()
Added code:
<script>
var obj = JSON.stringify([
{
"id":'1',
"name":'Jhon Doe',
"date":'April 14,2018'
},
{
"id":'2',
"name":'Coder',
"date":'April 23, 2018'
}
]);
var jsontoparse = JSON.parse(obj);
var i = obj.length;
var j=0;
while(j<=i){
console.log(jsontoparse[j].id);
j = j+1;
}
</script>

Related

Take a value in php page sent with jquery function

In this html page at the begin of the script i send the value of variable fin at the php page (http://sat3.altervista.org/index.php?valore="+ fin). In this php page i tried to take the value of variable but i didn't have success. Someone can help me?
<!doctype html>
<html>
<head>
<title>Parsing</title>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
</head>
<script>
var fin = "SAT000000002575";
url = "http://sat3.altervista.org/index.php?valore="+ fin,
data = {
get_param: 'value'
};
$.getJSON(url, data, function (data) {
for (var i = 0; i < data.length; i++) {
var lin = data[i]["Nr SAT"];
$('body').append($('<p>').html('Numero Sat: ' + data[i]["Nr SAT"] + ''));
$('body').append($('<p>').html('Data Apertura: ' + data[i]["Data Apertura"]));
}
});
</script>
<body>
<header>
</header>
</body>
</html>
This is the php page:
<?php
// Sopprimo gli errori del php
error_reporting(0);
// Includo la libreria
require_once 'excel_reader2.php';
$file_handle = fopen("leggimi2.csv", "r");
//EDIT: Define an array to hold individual lines
$data = array();
while (!feof($file_handle) ) {
//HERE I TAKE THE VALUE BUT IT DON'T CONTAIN NOTHING
$myValue = $_GET["valore"];
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] == $myValue)
{
$arr = array('Nr SAT' => $line_of_text[0],'Data Apertura' => $line_of_text[13], 'Tipo Servizio' => $line_of_text[1], 'Stato SAT' => $line_of_text[2],'Marca Terminale' => $line_of_text[4], 'Modello Terminale' => $line_of_text[5], 'IMEI guasto' => $line_of_text[6],'IMEI consegnato' => $line_of_text[7],'Famiglia guasto' => $line_of_text[8],'Descrizione guasto' => $line_of_text[9] );
//EDIT: Add the line to the array
$data[] = $arr;
}
}
//EDIT: Encode the array as a JSON array of line objects
echo json_encode($data);
//$myValue = isset($_GET['myValue']) ? $_GET['myValue'] : '';
fclose($file_handle);
?>
jQuery reference here http://api.jquery.com/jQuery.getJSON/ says that
second argument is "A plain object or string that is sent to the server with the request."
Try this:
<script type="text/javascript">
var fin = "SAT000000002575",
url = "http://sat3.altervista.org/index.php",
getVars = {
valore : fin
};
$.getJSON(url, getVars, function(data) {
// rest of your code
});
</script>
And let us know :)
EDIT
Regarding your PHP code, you have to put this $myValue = $_GET["valore"]; before your while begins.

Google stacked column chart giving an error

Hi I am trying for google stacked column charts. But I was getting the following error which I could not able to solve it. The error is "Uncaught TypeError: Cannot read property 'type' of null "
Here my code
<html>
<head>
<title></title>
</head>
<?php $con=mysql_connect("localhost","root", "innernet") or die("Failed to connect with database!!!!");
mysql_select_db("mobiledb", $con);
$user= $_GET['user'];
//echo $user;
$response["cols"] = array();
// $news = array();
//$news["id"] = "";
//$news["label"] = "ID";
//$news["type"] = "string";
//array_push($response["cols"], $news);
array_push($response["cols"], $news);
$news = array();
//$news["id"] = "";
//$news["label"] = "Q9a";
$news["type"] = "number";
array_push($response["cols"], $news);
$news = array();
//$news["id"] = "";
//$news["label"] = "Q9b";
$news["type"] = "number";
array_push($response["cols"], $news);
// $news = array();
// $news["id"] = "";
//$news["label"] = "ts";
// $news["type"] = "number";
// array_push($response["cols"], $news);
$result = mysql_query("SELECT `Q9a`, `Q9b` FROM goaltest WHERE id='$user'") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
$response["rows"] = array(); $table = array(); $rows = array();
while ($row = mysql_fetch_array($result))
{
$temp = array();
//$temp[] = array('v' => (string) $row['id']);
$temp[] = array('v' => (int) $row['Q9a']);
$temp[] = array('v' => (int) $row['Q9b']);
//$temp[] = array('v' => (int) $row['ts']);
array_push($response["rows"], array('c' => $temp));
}
//echo json_encode($response);
}
?>
<!--Load the AJAX API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["imagechart"]});
</script>
<script type='text/javascript'>
google.setOnLoadCallback(drawChart);
function drawChart() {
var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
var obj = eval ("(" + response + ")");
var dataTable = new google.visualization.DataTable(response);
var options = {cht: 'bvs', chs: '300x125', colors:['#4D89F9','#C6D9FD'],
chds:'0,160', chxl:'0:|oranges|apples|pears|bananas|kiwis|'};
var chart = new google.visualization.ImageChart(document.getElementById('bar_div'));
chart.draw(dataTable, options);
}
</script>
<body>
<div id='bar_div'></div>
</body>
</html>
So please any one tell me how to solve this
<html>
<head>
<title></title>
</head>
<!--Load the AJAX API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["imagechart"]});
</script>
<script type='text/javascript'>
google.setOnLoadCallback(drawChart);
function drawChart() {
var response = '{"cols":[null,{"type":"number"},{"type":"number"}],"rows":[{"c":[{"v":12},{"v":23}]},{"c":[{"v":37},{"v":55}]}]}'; alert(' hi ' + response);
var obj = eval ("(" + response + ")");
var dataTable = new google.visualization.DataTable(response);
var options = {cht: 'bvs', chs: '300x125', colors:['#4D89F9','#C6D9FD'],
chds:'0,160', chxl:'0:|oranges|apples|pears|bananas|kiwis|'};
var chart = new google.visualization.ImageChart(document.getElementById('bar_div'));
chart.draw(dataTable, options);
}
</script>
<body>
<div id='bar_div'></div>
</body>
</html>
(#asgallant has probably guessed right already.) In your first array_push(... $news) The $news is not yet defined. Consequently, the first array element under the "cols" property in the response variable is null. Maybe you just want to comment out that first array_push.

Problems with parsing a JSON object with jQuery

My php file does this:
<?php include('connection.inc.php'); ?>
<?php header("Content-type: application/json"); ?>
<?php
$sth = mysql_query("select * from ios_appointments a join ios_worker w join ios_partners p where a.workerid_fk = w.workerid and w.partnerid_fk = p.partnerid and p.code = 'DEMO6003'");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
?>
It returns this JSON output:
[{"appointmentId":"25","start":"2013-01-07 14:45:00","end":"2013-01-07 15:45:00","workerid_fk":"1","userid_fk":"22","isActive":null,"workerid":"1","prename":"Sarah","lastname":"Gonzalez","avatar":"megan.jpg","lineup":"Herren\/Damen","languages":"DE EN","partnerid_fk":"6","partnerid":"6","code":"DEMO6003","partnerName":"Demo Partner","street":"bla 1","zipCode":"bla","city":"bla","workers":"n\/a","email":"test#test.com","phone":"+41414441111","slogan":"Demo Partner zum Erkunden der App"},{"appointmentId":"26","start":"2013-01-10 11:15:00","end":"2013-01-10 12:15:00","workerid_fk":"1","userid_fk":"22","isActive":null,"workerid":"1","prename":"Sarah","lastname":"Gonzalez","avatar":"megan.jpg","lineup":"Herren\/Damen","languages":"DE EN","partnerid_fk":"6","partnerid":"6","code":"DEMO6003","partnerName":"Demo Partner","street":"bla 1","zipCode":"bla","city":"bla","workers":"n\/a","email":"test#test.com","phone":"+41414441111","slogan":"Demo Partner zum Erkunden der App"}, ...]
Now I try to parse the JSON output in a html file with this script:
<script type="text/javascript">
$.getJSON('<link to php file>', function(data) {
$.each(data, function(i, appointment) {
alert('entered each()');
var id = appointment.appointmentid;
console.log('appointmentid ' + id);
});
});
</script>
$.getJSON is called, but data is null. What am I doing wrong?
You just need to capitalize the i in appointment.appointmentid;
appointment.appointmentId; // <-- since your property has it capitalized

What am I doing wrong in the code?I am making a jquery/json call to call the data from the database

I have pasted the code for index.php and jsonPhp.php.I am new to JSON and learning json with ajax.Here,I am trying to get the data from the server using json.When I click on the link SERVER DATA, The data from the server must appear without re-loading the page using jQuery/json.I have written the code but I dont get it working.Please help.
Thanks.
<head>
<title>JSON WITH PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
type="text/javascript"></script>
<script type="text/javascript">
< ![CDATA[
$(function () {
$('#click').click(function () {
$.post('jsonPhp.php', function (data) {
//$("#content").html(data)+'<br>';
var pushedData = jQuery.parseJSON(data);
var htmlData = "";
//loop through using jQuery
$.each(pushedData, function (i, field) {
htmlData = htmlData + '-' + field.id + ',' + field.place + ',' + field.description + '<br>';
});
$('#content').html(htmlData);
});
});
});]] >
</script>
</head>
<body>Click on the link below to get the data from the Server Dynamicallly!
<br
/>
Server Data
<div id="content"></div>
</body>
<?php
$db = mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("places",$db) or die(mysql_error());
if(isset($_POST['place']))
$place=$_POST['place'];
if(isset($_POST['description']))
$description=$_POST['description'];
$myrows = array();
$result = mysql_query("SELECT * FROM search");
while( $row = mysql_fetch_assoc($result) ) {
$myrows[] = $row;
}
echo json_encode($myrows);
?>
Try specifying parameters, that you send with POST request, resulting something like this:
$.post('jsonPhp.php', { place:'myplace', /* other params */ }, function (data) { ...
Your jQuery post doesn't post the necessary items.
Be careful using this code.

Jquery autosuggest not working

Hey guys, I'm using jQuery's autosuggest plugin by using php to get the data. But it doesn't seem to work since I always get: No Results Found, even though I'm sure there are results:
Here's the php code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$input = mysql_escape_string($_GET["q"]);
$data = array();
$mysql=mysql_connect('localhost','***','***');
mysql_select_db('jmtdy');
$query = mysql_query("SELECT * FROM users WHERE username LIKE '%".$input."%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
And the script:
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest("suggestedf.php");
});
</script>
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest(
"suggestedf.php",
{
selectedValuesProp: "value",
selectedItemProp: "name",
searchObjProps: "name"
});
});
</script>
Add the above parameters, it will start to work :)
Just look at data, that server sends you back. If you use firefox you can watch it in network tab of firebug, or if you use chrome see it in resources.
The header must be in top of the file, right after the
<?php
header('Content-type: application/json');
include_once 'resources/dbconn.php';
$term = $_REQUEST['term'];
$query = "SELECT * FROM cds WHERE titel LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while ($obj = $result->fetch_array()) {
$arr[] = $obj;
}
//for jsonp echo '('.json_encode($arr).')';
echo json_encode($arr);
?>
The JS/jQuery string
<script type="text/javascript">
$(function() {
var cache = {},
lastXhr;
$("#exercise").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("json_Search.php", request, function(data,status,xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
});
</script>

Categories