json is not retrieving data - php
I'm new to json and I'm having problems retrieving this information i think is a cross domain issue but I can't get it to work.
PHP FILES:
include ('tew.php');
$converter = new Encryption;
$query="SELECT tbl_pizarra.idpizarra, tbl_pizarra.titulo, tbl_pizarra.imagenchica FROM tbl_pizarra ORDER BY idpizarra DESC LIMIT 3";
$sql=mysqli_query($tew,$query);
$datosJSON = '{"pizarra": [';
while($row=mysqli_fetch_array($sql)) {
$datosJSON .= '{
"idpizarra":"'.$converter->encode($row['idpizarra']).'",
"titulo":"'.$row['titulo'].'",
"imagenChica":"'.$rutaImagenes.$row['imagenchica'].'"
},';
}
$datosJSON .= ']}';
echo $datosJSON;
include ('tew.php');
$converter = new Encryption;
$query="SELECT tbl_pizarron.idpizarron, tbl_pizarron.titulo, tbl_pizarron.imagen FROM tbl_pizarron ORDER BY idpizarron DESC LIMIT 3";
$sql=mysqli_query($tew,$query);
$datosJSON = '{"pizarron": [';
while($row=mysqli_fetch_array($sql)) {
$datosJSON .= '{
"idpizarron":"'.$converter->encode($row['idpizarron']).'",
"titPizarron":"'.utf8_encode($row['titulo']).'"
},';
}
$datosJSON .= ']}';
echo $datosJSON;
JSON DATA:
{"pizarra": [{ "idpizarra":"xET8dKAk_F-4RlUq7brYPpGV3LvuC7pRBPm722FJQpU", "titulo":"Bienvenida y Agradecimiento casa 22", "imagenChica":"http://tuedificiowebdemo.com/images/pizarras/tew_Caminadora Suspiro 21386344709.JPG" },{ "idpizarra":"Nkblz3he-ABmNFbQNInKN89Mx6NWVar-YFqeUNjyWBM", "titulo":"proyecto Plantas", "imagenChica":"http://tuedificiowebdemo.com/images/pizarras/tew_foto1380142984.jpg" },{ "idpizarra":"ZaKIOE6yAVB8Q0YBNn13b-wdI9FYGoriIvMwumY7LdU", "titulo":"COMPRA DE LA CUBIERTA DE LA ALBERCA", "imagenChica":"http://tuedificiowebdemo.com/images/pizarras/tew_CubiertaDeAlberca21378356769.jpg" },]}
{"pizarron": [{ "idpizarron":"I0jks9aMm3znH1Mg__od5sd_buDp5H8zbisrPQkQj3o", "titPizarron":"FECHAS CORTES JARDINES" },{ "idpizarron":"dfa-LPljkeJWagSDMy5bjES3y6Drqn0EOxd568mYWy8", "titPizarron":"Cuota de Mantenimiento 2014" },{ "idpizarron":"yce4YmZ2ridNmkYr5Y1dU2TmTNI7EtdA2667F_5nEyQ", "titPizarron":"PROXIMAS FECHAS DE CORTE JARDINES" },]}
HTML FILE IM USING TO GET THE INFORMAITON:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$.getJSON("http://tuedificiowebdemo.com/tewMobile/php/noticiasPizarra2.php?jsoncallback=?",function(data) {
$.each(data.pizarra, function(i,data) {
var div_data = "<a href='documentos_detalles.html?id="+data.idpizarra+"' class='notiClick'><div><img src='images/alert.png' width=100' align='absmiddle'>"+" "+data.titulo+"</div></a>";
$(div_data).appendTo("#pizarra");
});
}
);
$.getJSON("http://tuedificiowebdemo.com/tewMobile/php/noticiasPizarron2.php?jsoncallback=?",function(data) {
$.each(data.pizarron, function(i,data) {
var div_data = "<a href='documentos_detalles.html?id="+data.idpizarron+"' class='notiClick'><div>"+data.titPizarron+"</div></a>";
$(div_data).appendTo("#pizarron");
});
}
);
return false;
});
});
</script>
<div id="pizarra"></div>
<div id="pizarron"></div>
ANY SUGESTION....
thanks.
Create an array in PHP and use json_encode $json = json_encode($array) to create a string with json data.
You are outputting 2 independent json strings which will not be read correctly. Both getJSON will get the same double invalid json string.
Invalid like your example:
{/*data here*/}
{/*data here*/}
Valid:
[
{/*data here*/},
{/*data here*/}
]
If it is a cross domain issue...include this header in the php page
header('Access-Control-Allow-Origin: *');
Related
How can use SQL query to get values from DB in arrays for a line chart
I'm trying to fetch data from DB for a line graph using the below code. <?php $dataPoints = array( $sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'"; $result1 = $conn->query($sql1); if ($result1->num_rows > 0) { while($row1 = $result1->fetch_assoc()) { array("y" => 25, "label" => "Sunday"), ?> } } else { } ); ?> <script> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { title: { text: "" }, axisY: { title: "" }, data: [{ type: "line", dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?> }] }); chart.render(); } </script> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> <div id="chartContainer" style="height: 370px; width: 100%;"></div> Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line However if i m to remove the sql query, graph plots with static data perfectly. Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript. <?php // import your mysqli connection before $result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'"); $dataPoints = $result1->fetch_all(MYSQLI_ASSOC); ?> <script> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { title: { text: "" }, axisY: { title: "" }, data: [{ type: "line", dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?> }] }); chart.render(); } </script> <?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be. $dataPoints = array(); $sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'"; $result1 = $conn->query($sql1); if ($result1->num_rows > 0) { while ($row = $result1->fetch_assoc()) { $dataPoints[] = $row; } }
Getting a JSON from a Ajax request and creating a polygon layer in Leaflet
I need some help with a script, i have an ajax request that returns a GeoJSON Images: JSON Format "id_map": "2", "description": "AC1", "geojson": {a GeoJSON coordinate } "file": "AC1.geojson" I can use AJAX JSON Leaflet (plugin( to create a polygon layer using the JSON value file ex (ac1.geojson) and point it up to a folder with the GeoJSON files (ex. geojson), but i have the same GeoJSON saved as a text variable in a database and i want to use it besides the file because of the risk of losing the files, so i recover it (i use GeoJson.io to validate the geojson and copy paste it in a column in my database) using a database connection and then i JSON encode it, but i am unable to use it. And I'm having problems with the format that comes out from the PHP. $(document).ready(function() { document.body.onload = function() { var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 20, minZoom: 13, attribution: 'x' }), latlng = L.latLng(-32.0312422, -52.0917713); var mymap = L.map('mapid', { center: latlng, zoom: 18, layers: [tiles] }); L.marker([-32.0312422, -52.0917713]).addTo(mymap); function popUp(f, l) { var out = []; if (f.properties) { for (key in f.properties) { out.push(key + ": " + f.properties[key]); } l.bindPopup(out.join("<br />")); } } var j_url = "somephp.php"; var results = $.ajax({ url: j_url, dataType: 'json', cache: false, success: AjaxSucceeded, error: AjaxFailed }); function AjaxSucceeded(results) { console.log("Data successfully loaded."); alert("OK"); $.each(results, function(index, value) { var geojsonTESTE = { "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [-52.101760, -32.031909], [-52.102275, -32.028598], [-52.100794, -32.028435], [-52.099206, -32.029053], [-52.097554, -32.029362], [-52.097511, -32.029672], [-52.096760, -32.029672], [-52.096696, -32.029544], [-52.095795, -32.029617], [-52.094142, -32.029835], [-52.088585, -32.030672], [-52.088392, -32.030763], [-52.088027, -32.034656], [-52.101631, -32.032145], [-52.101760, -32.031909] ] ] } }] }; var geoObject = JSON.parse(value.geojson); L.geoJSON(geojsonTESTE).addTo(mymap); L.geoJSON(features).addTo(mymap); //With Leaflet Ajax e Files //j_url = "json/"+value.file; //var jsonTest = new L.GeoJSON.AJAX([j_url]{onEachFeature:popUp}).addTo(mymap); }); } function AjaxFailed(results) { console.log("ERROR AJAX"); alert("ERRO"); } $.when(results).done(function() { }); }; }); <?php header('Content-Type: application/json'); $connStr = { database connection string } $conn = pg_connect($connStr); $result = pg_query($conn, "select * from mapas"); $qtd = pg_num_rows($result); $res = "["; if($qtd > 0){ $i = 0; foreach(pg_fetch_all($result) as $row) { $x = $row['geojson']; $patterns = array ('/[^A-Za-z0-9\-\,\"\:\{\}\[\]]/'); $replace = array (''); $desc = preg_replace($patterns, $replace,$x); $desc = str_replace('\"', '"', $desc, $count); $data['id_map'] = $row['id_map']; $data['description'] = $row['description']; $data['geojson'] = $desc; $data['file'] = $row['file']; $map = json_readable_encode($data,null,true); $res .= $map; if($i < $qtd -1 ){ $res .= ","; } $i++; } } $res .= "]"; echo trim($res); pg_free_result($result); pg_close(); ?>
My ajax code doesnt output JSON file
So ive been trying to get this to work for hours now but im just stuck. I have a simple guestbook page setup and I have this code creating a JSON file: <?php /* Konstanter för db-inställningar */ define("DBHOST", "localhost"); define("DBUSER", "guestbook"); define("DBPASS", "password"); define("DBDATABASE", "guestbook"); /* DB-anslutning */ $db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBDATABASE) or die('Fel vid anslutning'); $numrows = 999; // Maxvärde if(isset($_GET['numrows'])) { $numrows = intval($_GET['numrows']); } /* SQL-fråga */ $sql = "SELECT * FROM users LIMIT $numrows"; $result = mysqli_query($db, $sql) or die('Fel vid SQL-fråga'); /* Loopa genom resultet och spara till ny array */ $rows = mysqli_fetch_all($result, MYSQLI_ASSOC); $json = json_encode($rows, JSON_PRETTY_PRINT); header('content-type: application/json; charset=utf-8'); header("access-control-allow-origin: *"); echo $json; This outputs it in JSON format and then I have this code trying to read the file and output the content of the JSON to this page: <!DOCTYPE html> <html lang="sv"> <head> <meta charset="utf-8"> <title>Guestbook</title> </head> <link rel="stylesheet" href="css/stilmall.css?<?php echo time(); ?>" type="text/css"> <body> <nav id="mainmenu"> <ul> <li>Home</li> <li>Administration</li> <li>JSON</li> <li>Webbservice</li> </ul> </nav> <div class="posts"> <h2>WebService</h2> <div id="info"></div> <script> var xhr = new XMLHttpRequest(); // läs ut svar xhr.onload = function() { if(xhr.status === 200) { console.log(xhr.responseText); var jsonStr = JSON.parse(xhr.responseText); var users= jsonStr.posts; for(var i=0; i<users.lenght; i++) { document.getElementById("info").innerHTML = xhr.responseText; } } }; xhr.open("GET","http://localhost/webbutveckling2/moment3/webservice.php",true); xhr.send(null); </script> </p> </div> </body> </html> I cannot for the love of good see what im doing wrong. I need this to output the JSON content, also I would like to just output the 3 latest entried from the JSON file only. What im doing wrong? Edit: Here is the JSON output: [ { "id": "2", "name": "Emil1234", "post": "My name is Emil and this is a test for a post on the guestbook wall", "postdate": "2018-03-15 16:41:10" }, { "id": "22", "name": "golddigger", "post": "Hi! This is my first visit to this epic guestbook", "postdate": "2018-03-25 14:52:11" }, { "id": "23", "name": "Tester123", "post": "Im just doing another test dont mind me", "postdate": "2018-03-25 14:52:31" }, { "id": "24", "name": "the bluff", "post": "Whatsup all", "postdate": "2018-03-25 15:17:17" } ] When I update my code in the js to the following: <script> var xhr = new XMLHttpRequest(); // läs ut svar xhr.onload = function() { if(xhr.status === 200) { console.log(xhr.responseText); document.getElementById("info").innerHTML = xhr.responseText; </script> It does put out the raw information in the following way: How do I output this to be show just the latest 3 posts? Edit 2: <script> var xhr = new XMLHttpRequest(); // läs ut svar xhr.onload = function() { if(xhr.status === 200) { console.log(xhr.responseText); document.getElementById("info").innerHTML = xhr.responseText; //var jsonStr = JSON.parse(xhr.responseText); var users = JSON.parse(xhr.responseText); for(var i=0; i < users.length; i++) { document.getElementById("info").innerHTML = users[i].name + " - " + users[i].post + " - " + users[i].postdate ; } } }; xhr.open("GET","http://localhost/webbutveckling2/moment3/webservice.php?numrows=3",true); xhr.send(null); </script> This outputs just one, is my url wrong? Outputs the following:
There is not " numrows " is going as a get request in the ajax call thatsand just try putting the fetch function in a while loop and concatenate in the output variable
ExtJS 5.1, grid load data from database with PHP
I am doing an online course of Ext JS 5.1 and in this exercise I have a service.php file which connects to database and returns JSON Data. I try to show this data but it never gets displayed (doesn't show any error message in firebug) and I can`t find what is the problem with the code. This is the code of the store: var storeUsuario = Ext.create('Ext.data.Store', { model : 'js.clase.Usuario', proxy: { type: 'rest', url: 'service.php?method=getUsuarios', reader: { type: 'json', } }, autoLoad: true }); This is the code of the grid: Ext.create('Ext.grid.Panel', { renderTo: Ext.getBody(), store: storeUsuario, width: 600, height: 400, title: 'Grid Usuarios', columns: [ { text: 'id', dataIndex: 'id' },{ text: 'nombre', width: 100, dataIndex: 'nombre' },{ text: 'apellidos', dataIndex: 'apellidos' },{ text: 'email', dataIndex: 'email' },{ text: 'nacionalidad', dataIndex: 'nacionalidad' },{ text: 'rutaAvatar', dataIndex: 'rutaAvatar' } ] }); and the service.php method: <?php header('Content-Type: text/html; charset=utf-8'); $conexion = mysql_connect("127.0.0.1", "root", ""); mysql_select_db("usertest", $conexion); $method = $_GET['method']; switch($method) { case "getUsuarios": $query = "SELECT * FROM Usuario ORDER BY id ASC"; $result = mysql_query($query, $conexion) or die(mysql_error()); $numRows = mysql_num_rows($result); $usuarios = array(); if ($numRows > 0) { $i = 0; while ($row = mysql_fetch_assoc($result)) { $usuarios[$i] = $row; $i++; } } $usuariosJSON = json_encode($usuarios); echo $usuariosJSON; break; } ?>
Your PHP code doesn't return a valid JSon. See this fiddle works correctly: https://fiddle.sencha.com/#fiddle/q9k
According to this post you should specify the header. And I suggest you to return a "hand formed" json like this: $data = /** whatever you're serializing **/; $data_length = /* the length of the result according to the request response */; header('Cache-Control: no-cache, must-revalidate'); // just to be sure header('Content-Type: application/json'); echo "{ \"success\": true, \"total\": $data_length, \"records\": " . json_encode($data) . " }"; The json data could need []... echo "{ \"success\": true, \"total\": $data_length, \"records\": [ " . json_encode($data) . " ] }";
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); }); }); });