Hi I've been given the task of formatting JSON using any form of client side. At the moment the JSON is outputted in a standard format like this.
{"Art":[["1","Game Weapons","Weapons","11","GameWeapons_Final_Sheet.jpg"],["2","Violet","Scenery","11","Violet_sheetformat.jpg"]]}
To do this I am using PHP to extract the data and then encode
$jsondata = array();
while($row=mysqli_fetch_row($result))
{
$jsondata['Art'][]=$row;
}
echo json_encode($jsondata);
How do I go about formatting this data before printing and again it has to be client side. Nothing fancy is needed, just simple indenting so it can be read easier. Apologies if I've incorrectly posted or my question doesn't make sense
EDIT
I need my JSON to be indented like this using any client side language
{
"Art":[
[
"1",
"Game Weapons",
"Weapons",
"11",
"GameWeapons_Final_Sheet.jpg"
],
[
"2",
"Violet",
"Scenery",
"11",
"Violet_sheetformat.jpg"
]
]
}
EDIT 2
current code
<?php
include ("config/init.php");
$connection = mysqli_connect($hostname, $username, $password, $databaseName) or die("you did not connect");
$query = "SELECT * FROM art";
$result = mysqli_query($connection, $query) or die (mysqli_error($connection));
$jsondata = array();
while($row=mysqli_fetch_row($result))
{
$jsondata['Art'][]=$row;
}
$json = json_encode($jsondata);
?>
<script>
var obj = <?php echo $json; ?>;
var str = JSON.stringify(obj, undefined, 2);
document.write(str);
</script>
All done now, thankyou so much
Try json_encode($jsondata, JSON_PRETTY_PRINT);
For more information check the PHP manual.
If they are so insistant of doing the formatting front end, you could do something like this:
<?php
$jsondata = array();
while($row=mysqli_fetch_row($result))
{
$jsondata['Art'][]=$row;
}
$json = json_encode($jsondata);
?>
<script>
var obj = <?php echo $json; ?>;
var str = JSON.stringify(obj, undefined, 2);
</script>
Related
I am having trouble with Full Calendar (FC) to read the JSON object I have returned from my database to display events on the calendar. Where could I be overlooking?
My jQuery for FC is here:
$('#calendar').fullCalendar({
defaultView: 'month',
titleFormat: "MMMM YYYY",
header: {
left: 'month,agendaWeek,agendaDay',
center: 'title',
right: 'prevYear,prev,next,nextYear'
},
events: {
url: "../ajax/tutor/json_events.php",
type: "POST",
color: "yellow",
textColor: "black",
error: function() {
alert('There was an error while fetching events.');
}
}
});
The json_events.php is here:
$returnArray = array();
$userID = filter_input(INPUT_GET, "id");
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Lessons WHERE TutorID = 1");
if($stmt->execute()){
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$rowArray['start'] = $row['Start'];
$rowArray['end'] = $row['End'];
$rowArray['title'] = $row['CourseTaught'];
array_push($returnArray, $rowArray);
}
$json = json_encode($returnArray);
}
echo print_r($json);
$stmt->close();
The JSON object displays perfectly, however the alert is being thrown from jquery events for some reason, I am just overlooking the error somehow. A fresh pair of eyes would be useful.
Add square brackets around $json, something like echo('['.$json.']');
You are returning a human-readable dump of the variable in PHP by using print_r(). Your JavaScript is expecting the true JSON object without formatting.
Simply echo $json; instead of echo print_r($json); and you will get your json object without the surrounding <pre> tags.
I am new to angularJS and has very few knowledge on javascript.
I am trying to retrieve data from database by using the $http.post method. below is what I get from the .php file.
[{
"ticketid": "1484637895",
"categoryid": "1",
"subcategoryid": "2",
"ciphonenum": "01814149028",
"calldescription": "The customer wanted to know all the SKU of Bashundhara Baby Diaper and he requested to inform him through the mail.",
"ccrreply": "CCR sent him all SKU of Diaper including the M.R.P.",
"ccraction": "N\/A",
"output": "N\/A",
"remarks": "N\/A",
"contactinfoname": "MD.Masud",
"ciaddress": "Banani,DOHS\nDhaka."
}]
Here is what my php file looks like
<?php
$data = json_decode(file_get_contents("php://input"));
require 'db-config.php';
$ticketid = $data->id;
$sql = "SELECT t.ticketid, t.categoryid, t.subcategoryid, td.ciphonenum, td.calldescription, td.ccrreply,
td.ccraction, td.output, td.remarks, ci.contactinfoname, ci.ciaddress FROM ticketdetails td
INNER JOIN tickets t on t.ticketid = td.ticketid
INNER JOIN contactinfodetails ci ON ci.ciphonenum = td.ciphonenum WHERE t.ticketid = '$ticketid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
?>
Below is the function in angularjs which generate the post request
$scope.showTicket = function() {
var id = $routeParams.id;
$http.post('api/showTicket.php',{'id':id}).then(function(response){
$scope.ticket = response.data;
console.log($scope.ticket);
});
};
I want display only the ticketid and calldescription from the array but whenever I assign value like
$scope.ticketid = $scope.ticket.ticketid;
it says undefined variable. Please help....
Your JSON is an array of objects, and not an object.
So instead of doing $scope.ticketid = $scope.ticket.ticketid, try:
$scope.ticketid = $scope.ticket[0].ticketid;
As your array only contains one object, it is probably the solution...
I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.
I'm attemping to use this code to call a php file, access the database, retrieve values, and return them using a JSON object, then edit them into a text box.
Code for Javascript end:
As the user changes the option in the dropdown list, the app should call a PHP script to fetch the new values from the database, retrieve them from a JSON object, and modify a text area to show the new values.
<select id="busSelect" name="busSelect">
<option>S053-HS - P</option>
<option>S059-HS - P</option>
<option>S064-HS - P</option>
<option>S069-HS - P</option>
<option>S070-HS - P</option>
</select>
<textarea id="memo"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js" type="text/javascript"></script>
<script type ="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript">
<?php
?>
dojo.ready(function(){
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(26.4615832697227,-80.07325172424316),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(dojo.byId("map_canvas"),
myOptions);
dojo.connect(busSelect,"onchange",function(){
dojo.xhrGet({
url: "getRoute.php",
handleAs: "json",
timeout: 1000,
content: {
route: dojo.byId("busSelect").value
},
load: function(result) {
var formResult = result.lat_json + " " + result.long_json + " " + result.name_json;
dojo.byId(memo).value = formResult;
}
});
});
PHP Script:
Should take the name it receives from the JS app, which is the "bus name" and find the bus id using that name. Then it should access bus stops using that ID (this all works, I'm just getting the JSON/AJAX bit wrong)
<?php
header('Content-type: application/json');
require_once 'database.php';
mysql_connect($server, $user, $pw);
mysql_select_db("busapp") or die(mysql_error());
$route = $_GET["route"];
$result_id = mysql_query("SELECT * FROM routes WHERE name = $route");
$result_row = mysql_fetch_array($result_id);
$route_id = $row['id'];
$result = mysql_query("SELECT * FROM stops_routes WHERE route_id = $route_id")
or die(mysql_error());
$markers;
$stopid = array();
$time = array();
$lat;
$long;
$name;
$waypts = array();
for ($x = 0; $row = mysql_fetch_array($result); $x++) {
$stopid[$x] = $row['stop_id'];
$time[$x] = $row['time'];
}
for ($x = 0; $x < sizeof($stopid); $x++) {
$result = mysql_query("SELECT * FROM stops WHERE id = $stopid[$x]")
or die(mysql_error());
$row = mysql_fetch_array($result)
or die(mysql_error());
$lat[$x] = $row['lat'];
$long[$x] = $row['long'];
$name[$x] = $row['name'];
}
$size = count($stopid);
$lat_json = json_encode($lat);
$long_json = json_encode($long);
$name_json = json_encode($name);
?>
I'm also getting an error on dojo.xd.js:14 when running.
Instead of individual variables passed to json_encode(), you should be creating an object and then encoding it as JSON, then simply echoing out the JSON with the correct Content-type header.
// Start with an associative array
$arr = array("lat_json" => $lat, "long_json" => $long, "name_json" => $name);
// Cast it to an Object of stdClass
$obj = (object)$arr;
// Encode it
$json = json_encode($obj);
// And return it to the calling AJAX by just echoing out the JSON
header("Content-type: application/json");
echo $json;
exit();
Before encoding JSON, your object now looks like (with my example data):
stdClass Object
(
[lat_json] => 12345
[long_json] => 45678
[name_json] => the name
)
// After json_encode()
{"lat":12345,"long":45678,"name":"the name"}
As you've setup your javascript on the receiving end, I believe it should work without modification. To be certain of the JSON structure from the javascript end, be sure to check console.dir(result) inside your load() function.
I am trying to create a drop down list using jQuery, PHP and mySQL, here is my code thus far,
HTML:
<select id="box"></select><br />
<input id="button" type="button" value="populate" />
Javascript/jQuery:
$(document).ready(function() {
$("#button").click(function (){
$.getJSON("test_post.php", function(data){
$.each(data, function(user) {
$('#box').append(
$('<option></option>').html(user)
);
});
});
});
});
PHP:
mysql_connect('localhost', 'user', '1234');
mysql_select_db('json');
$test = mysql_query('SELECT user,pass FROM login WHERE user="john"');
while($row = mysql_fetch_array($test, true)) {
$data .= json_encode($row);
};
echo $data;
I have 3 entries in the database, and when I run the 'test_post.php' file, it echoes out the JSON, but when I try and get it to populate the drop down, nothing happens!
Any idea why?
Try taking json_encode out of while loop and encoding it at the end. Like this:
while($row = mysql_fetch_array($test, true))
{
$data[] = $row;
}
$data = json_encode($data);
echo $data;
[EDIT]: After OP comment:
If you just want the name of the user in the drop down, then do it like this:
while($row = mysql_fetch_assoc($test))
{
$data[$row['user']] = $row;
}
$data = json_encode($data);
echo $data;
There are several problems in your code.
First: attempt to use undefined variable $data, you should have initialized it to an empty string before while loop: $data = '';, otherwise this can send PHP notice with the JSON response, depending on values of display_errors and error_reporting settings.
Second: as #shamittomar said, $data must be an array and json_encode() must be called only once for the whole array. For now, you're sending several JSON objects concatenated to a single string, which is wrong.
Third: value of the user function parameter in the JavaScript is actually an index of the data array, not a value, but even if user would be a value, it would be a JavaScript object with user and pass properties, not a string.
Resulting code should be (changed parts only):
PHP
$data = array();
while ($row = mysql_fetch_array($test, true)) {
$data[] = $row;
};
echo json_encode($data);
JavaScript
$.each(data, function(i, user) {
$('#box').append(
$('<option></option>').html(user.user)
);
});
Have you tried validating the JSON?
jQuery is quite picky about it's JSON: it needs to validate correctly, no comments and the right content-type!
Try adding the following in your PHP to see if it helps (I always do this)
header('Content-type: application/json');
First of all check mysql connection code is ok?
mysql_connect('localhost', 'user', '1234');
Updated php code as below,
mysql_connect('localhost', 'user', '1234');
mysql_select_db('json');
$test = mysql_query('SELECT user,pass FROM login WHERE user="john"');
while($row = mysql_fetch_array($test, true)) {
$data['pass '] = $row['pass'];
$data['user'] = $row['user'];
};
echo json_encode($data); die();
Javascript code:
$("#button").click(function (){
$.getJSON('getDropdownData.php', '',function(data){
$("#box").remove();
$('<option />', {value: '', text: 'Select option'}).appendTo("#box");
$.each(data,function(key, value){
$('<option />', {value: key, text: value}).appendTo("#box");
});
});
});
Then you will get a dorpdown with pass as "option value" and user as "option text".