How do I import PHP array in a JSON array? - php

So I have a PHP script where I ask a simple query and then I put it in an array.
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
The outcome of print json_encode($data) is:
[{"ATX12V":"10"},{"ATX12V":"65"},{"ATX12V":"64"},{"ATX12V":"96"}]
Below I have a javascript code and my question is how do I add $data to the data[]??
<script>
var buyerData = {
labels : ["January","February","March","April","May","June", "July", "August"],
datasets : [
{
fillColor : "#9DB86D",
strokeColor : "#ACC26D",
pointColor : "#9DB86D",
pointStrokeColor : "#9DB86D",
data : []
}
]
}
</script>

What about simple:
data : <?php echo json_encode($data); ?>

you can use ajax like :
(home.html):
<script type="text/javascript">
window.onload = function() {
$.ajax({
type: "POST",
url: "request.php",
dataType: "json",
success: function (data) {
alert(data[0].ATX12V);
}
});
}
</script>
<script type="text/javascript" src="js/jquery.js"></script>
and server side (request.php) :
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
note: Add jquery.js in your project

Related

Get ajax json data individually

I have a slight problem with my code, lets say i have a json like this one :
[{"img":"john.png","name":"John","username":"#john"},
{"img":"mark.png","name":"mark","username":"#mark"}]
I wanna get data organized like :
John #john john.png
Mark #mark mark.png
But every time the data comes out like this:
John Mark #john #mark john.png mark.png
This is my Php Code:
<?php
class search{
public function gettingvalues($search_value){
require_once('conx.php');
$dir = "usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json;
}
echo json_encode($results);
}
}
}
}
?>
This the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var img = [];
var username = [];
var name = [];
$.each(json_data, function(index, element) {
img.push(element.img);
username.push(element.username);
name.push(element.name);
})
$('#feedback').html('');
$('#feedback').html(name+username+img);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Actually this is my first time with json, i don't know what is the problem or maybe i missed something, I hope getting some answers.
You need to build the HTML in the order that you want it displayed.
var html = '';
$.each(json_data, function(index, element) {
html += `${element.name} ${element.username} ${element.img}<br>`;
}
$("#feedback").html(html);

Live Search results from database using AJAX, JSON

my script returns an array of JSON, and not individual results from the database. The script is designed to retrieve from the database records that match the text you typed. Below my codes, what could be wrong?
PHP:
//after connect to database (succesfull)
if($_GET['search_data'])
{
$search = ltrim($_GET['search']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: "text=" + text,
async: false,
success: function(text) {
if(text)
{
$('#display').append(JSON.stringify(text))
}
else
{
$('#display').append('No results!');
}
}
});
});
});</script>
<title>Live search</title>
</head>
<body>
<br />
search: <input type="textbox" value="" name="search" placeholder="Write here..." id="search" />
<br />
<div id="display"></div>
</html>
and results:
[{"id":"10","text":"Dropdowns"},{"id":"9","text":"Accordions"},{"id":"5","text":"Convert Weights"},{"id":"3","text":"Animated Buttons"},{"id":"8","text":"Side Navigation"},{"id":"6","text":"Parallax"},{"id":"2","text":"HTML Includes"},{"id":"7","text":"Progress Bars
"},{"id":"4","text":"Top Navigation"},{"id":"1","text":"Range Sliders"},{"id":"11","text":"Google Maps"}]
My problem is that it shows when you type some letters the whole array of JSON, and not only the record, which we expect. What can I do?
You're trying go get the search parameter with $_GET['search'] you need to use $_POST['text']. Try this :
if($_GET['search_data'])
{
$search = ltrim($_POST['text']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
if(!empty($search)
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
And it's a good practice to use object in your ajax data
$(document).ready(function () {
$("#search").keyup(function () {
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: {
text: text
},
async: false,
success: function (text) {
if (text)
{
$('#display').append(JSON.stringify(text))
} else
{
$('#display').append('No results!');
}
}
});
});
});

Chart from Database

I am trying to implement a chart from database, but I'm having a few problems...
I have a Database with 2 rows: Date, Pcr
My files .php:
Data.php
$query = "SELECT * FROM `table1` ORDER BY Date LIMIT 0 , 100";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
$dates=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$dates[] = $row['Date'];
$dates[] = $row['Pcr'];
}
echo json_encode($dates);
I get the array:
["2015-06-14","0.77","2015-06-20","0.79","2015-09-24","0.88","2015-10-26","0.8","2015-10-30","0.7"]
I would like to get a dynamic chart from this array, but I don't know how to do that...
I have this static file:
chart.php
<div class="resultados"><canvas id="grafico"></canvas></div>
<script>
$(document).ready(function(){
$.ajax({
type:'POST',
url:'data.php',
success:function(data){
var valores = eval(data);
var date1 = valores[0];
var pcr1 = valores[1];
var date2 = valores[2];
var pcr2 = valores[3];
var date3 = valores[4];
var pcr3 = valores[5];
var date4 = valores[6];
var pcr4 = valores[7];
var Datos = {
labels : [date1,date2,date3,date4],
datasets : [
{
fillColor : 'rgba(255,0,0,0.1)',
strokeColor :'rgba(255,0,0,100)',
pointColor : 'rgba(255,0,0,100)',
pointStrokeColor:"#e32636",
pointHighlightFill:"#bbf",
pointHighlightStroke:"rgba(255,0,0,255)",
data : [pcr1,pcr2,pcr3,pcr4]
}
]
}
var contexto = document.getElementById('grafico').getContext('2d');
window.Barra = new Chart(contexto).Line(Datos, { responsive : true });
}
});
return false;
}
)
</script>
Could someone help me to find what I have to put in Data:[]?
Thank you very much
php:
$dates=array();
$pcrs=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$dates[] = $row['Date'];
$pcrs[] = $row['Pcr'];
}
$data = ["dates"=>$dates,"pcrs"=>$pcrs];
echo json_encode($data);
js:
$(document).ready(function(){
$.ajax({
type:'GET',
url:'data.php',
success:function(data){
var Datos = {
labels : data.dates,
datasets : [
{
fillColor : 'rgba(255,0,0,0.1)',
strokeColor :'rgba(255,0,0,100)',
pointColor : 'rgba(255,0,0,100)',
pointStrokeColor:"#e32636",
pointHighlightFill:"#bbf",
pointHighlightStroke:"rgba(255,0,0,255)",
data : data.pcrs
}
]
}
var contexto = document.getElementById('grafico').getContext('2d');
var chrt = new Chart(contexto).Line(Datos, { responsive : true });
}
});
return false;
}
)

Highstock json data not showing

Hey guys I am having trouble loading my data into the highstock charts.
My json.php calls on a sample MySQL database and looks something like this:
$result = mysql_query("SELECT UNIX_TIMESTAMP(date)*1000 AS timestamp,value from sample") or die('Could not query');
if(mysql_num_rows($result)){
echo 'Test';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
if($first) {
$first = false;
} else {
echo ',';
}
$json_str = json_encode($row, JSON_NUMERIC_CHECK);
echo $json_str;
}
if(array_key_exists('callback', $_GET)){
$callback = $_GET['callback'];
echo $callback. '('.$json_str.');';
}
} else {
echo '[]';
}
mysql_close($db);
My index.htm which calls the Json.php is from the sample highstock template I just merely changed the getJson to match with my reference. Here is the code. Any help would be much appreciated, thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('json.php', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'Test'
},
series : [{
name : 'Test',
data : data,
marker : {
enabled : true,
radius : 3
},
shadow : true,
tooltip : {
valueDecimals : 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
Also, my json is parsed in this manner:
Test[1370899026000,10],[1370899026000,4],[1368177426000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1378826226000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,9],[1370899026000,9],[1370899026000,10],[1370899026000,6],[1370899026000,6],[1370899026000,6],[1370899026000,12],[1370899026000,7],[1370899026000,12],[1370899026000,8],[1370899026000,13],[1370899026000,12],[1370899026000,9],[1370899026000,7],[1370899026000,7],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,9],[1370899026000,10],[1370899026000,4],[1370899026000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1370899026000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7]
Try closing with
[]
Highstock fiddle: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/areaspline/
Data of that fiddle: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
Please take look at http://docs.highcharts.com/#preprocessing-data-from-a-database and take look at very simple example with json_encode:
tmp = array();
$tmp[] = array('A',5);
$tmp[] = array('B',6);
$tmp[] = array('C',1);
$tmp[] = array('D',2);
$rows = array();
for($i=0; $i<count($tmp); $i++)
{
$row['name'] = $tmp[$i][0];
$row['data'] = array($tmp[$i][1]);
array_push($rows,$row);
}
print json_encode($rows);
Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{
name: 'Browser share',
data: []
}]
}
$.getJSON("datavotecolum.php", function(json) {
console.log(json);
options.series = json;
chart = new Highcharts.Chart(options,function(chart){
console.log(chart.series);
});
});
});

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