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.
Related
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>
The code's that I have is executing fine but after I included the loop that was suggested to me the problem is that the data it retrieves shows only [Object Object]
here is my current progress
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
}
Here is my JS
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
res is a jQuery object (as created by $([]) and populated by res.add
You're outputting an object into a string context (HTML) so of course it will result in [object Object] - that's just how objects are converted to string.
Consider... not using jQuery where it's not needed.
var res = [], out = document.getElementById('clog'), div;
while(out.firstChild) out.removeChild(out.firstChild);
$.each(result[0], function(key, value) {
div = document.createElement("div");
div.appendChild(document.createTextNode(value});
res.push(div);
out.appendChild(div);
}
First of all check your input array in php side. And show it. Second step is to RE-CHECK manual on http://www.php.net/manual/en/function.json-encode.php and look on depth param.
JS side won't help if you sending wrong params/array/json.
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 a noob to jquery and i want to know how to make use of if else for the following:
on the server side there is a if for number of rows is equal to 0 and else some JSON part.
$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
{
echo "true";
}
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output = array('title' => $row['title'],'age' => $row['age']);
}
echo json_encode($abc_output);
}
Now coming to Jquery part :
If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.
$(document).ready(function(){
$("#button1").click(function(){
$.getJSON('script_1.php',function(data){
if (data=='true') {
alert ('hello')
}
else {
$.post('script_1.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
},
"json");
}
});
});
Edited:
$(document).ready(function(){
$("#button1").click(function(){
$.post(
'script.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
var data = JSON.parse(json);
if (data.length === 0){
alert('no data');
}
else{
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
}},
"json"
);
});
});
PHP side
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row= array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.
For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
echo json_encode($row);
} else {
echo json_encode(array());
}
Back in the JavaScript, you could then do something like this:
var data = JSON.parse(json);
if (data.length === 0) {
alert('no data');
} else {
$("input[name='title']").val(data.title);
$("input[name='age']").val(data.age);
}
jeroen is right though, you only need to use one AJAX call.
There seem to be a few problems:
You are treating the data returned from getJSON as if it is plain
text
The php that you are calling from javascript does not always
return json
You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition
By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.
Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:
$.getJSON('script_1.php',function(data){
to something like:
$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {
and in your php you need to use something like:
$name = mysql_real_escape_string($_GET['id']);