How to write json encoded data into a json file? - php

I am trying to get json encoded data into a json file inorder to show them in an event calendar.I am using php codeigniter framework.I just want to know whether is there any other method other than the method i have used. Because it is not working. But when i echo the json_encode data it displays.But I want to write them into a separate file calls events.json.
Thanks in advance.
model
function get_all_reservations_for_calendar(){
$this->db->select('reservations.date,reservations.time,reservations.hall');
$this->db->from('reservations');
$this->db->where('is_deleted', '0');
$query = $this->db->get();
return $query->result();
}
Controller
function index() {
$reservation_service = new Reservation_service();
$output['calendar_results'] = $reservation_service->get_all_reservations_for_calendar();
$partials = array('content' => 'dashboard/dashboard_view');
$this->template->load('template/main_template', $partials, $output);
}
calendar_view
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
#event_cal{
width: 500px;
height: 500px;
}
</style>
<link rel="stylesheet" href="http://localhost/Calendar/backend_resources/css/eventCalendar.css">
<link rel="stylesheet" href="http://localhost/Calendar/backend_resources/css/eventCalendar_theme_responsive.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://localhost/Calendar/backend_resources/js/jquery.eventCalendar.min.js" type="text/javascript"></script>
<?php //echo json_encode($calendar_results); ?>
<?php
//write to json file
$fp = fopen('events.json', 'w');
fwrite($fp, json_encode($calendar_results));
fclose($fp);
?>
<script type="text/javascript">
$(function() {
$("#event_cal").eventCalendar({
eventsjson: 'http://localhost/Calendar/backend_resources/json/events.json',
dateFormat: 'dddd MM-D-YYYY'
});
});
</script>
</head>
<body>
<div id="event_cal" ></div>
</body>
</div>

You can put your file data using file_put_contents();
<?php
//write to json file
$jsonEvents=json_encode($calendar_results);
file_put_contents('events.json',$jsonEvents);
?>

Related

how to avoid header and footer html code when getting data from ajax in zend framework?

I am having some problem with the ajax . I want to get image name only using ajax but I am getting header and footer content instead of image name..
here is my code.
controller file
public function deleteimageAction() {
$id = (int) $this->params()->fromRoute('id', 0);
$image = $_POST['image'];
return $image;
}
and my ajax-
$('.delete').click(function(e){
var imageName=$(this).attr('data');
var id=$(this).attr('id');
$.ajax({
url:'/test/zend/public/business/deleteimage/'+id,
type: 'POST',
data:{id:id,image:imageName,},
success: function (data) {
alert('Success : please check console')
console.log(data);
},
error:function(data) {
alert('Error : please check console')
console.log(data);
}
});
});
and getting the following result in the console -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ZF2 Skeleton Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Le styles -->
<link href="/test/zend/public/css/bootstrap.min.css" media="screen" rel="stylesheet" type="text/css">
<link href="/test/zend/public/css/style.css" media="screen" rel="stylesheet" type="text/css">
<link href="/test/zend/public/css/bootstrap-responsive.min.css" media="screen" rel="stylesheet" type="text/css">
<link href="/test/zend/public/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon">
<!-- Scripts -->
<script type="text/javascript" src="/test/zend/public/js/jquery.min.js"></script>
<script type="text/javascript" src="/test/zend/public/js/bootstrap.min.js"></script>
<!--[if lt IE 9]><script type="text/javascript" src="/test/zend/public/js/html5.js"></script><![endif]-->
</head>
<body>
</body>
</html>
public function deleteimageAction() {
$id = (int) $this->params()->fromRoute('id', 0);
$image = $_POST['image'];
echo $image;
exit();
}

yii2 doesnt set cookies when calling render method

I try to set cookie with this action in a yii2 controller:
public function actionContact() {
$cookie = new Cookie([
'name' => 'test_name',
'value' => 'test_value'
]);
Yii::$app->getResponse()->getCookies()->add($cookie);
return $this->render('contact');
}
But it doesnt work like this. Meanwhile if I do it without rendering the contact view, it does work. It also works if I use
return $this->redirect('anothercontroller');
instead of
return $this->render('contact');
If I use it without layout ($this->layout = false) then it also works.
Is the html header in the layout file overwriting the previous info?
The skeleton of the layout file is this:
<?php
use yii\helpers\Url;
//etc...
AppAsset::register($this);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="/img/logo4.xcf" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="format-detection" content="telephone=no">
<title>Title</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.load('current', {'packages':['gauge']});
google.charts.load('current', {'packages': ['geochart'],
'mapsApiKey': 'AIzaSyDW77Ajhkkj0-c70o5lXawp89Sfj81TI'
});
</script>
<?= Html::csrfMetaTags() ?>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
Is there any workaround?
Thanks for your time!

How do I access the datafields in the source object of a jqxlistbox

I'm trying to bind a JQXListbox to JSON data and display two fields in the result.
I want to access the datafields in the source object as strings in order to concatenate them so as I can set the resulting string as the displayMember property of jqxListBox. I've tried calling ToString() on the source.datafields[x] array but that doesn't work either.
I'm not sure if the terminology was correct there. Thanks for any help you can give.
Here is the code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="scripts/jqwidgets/styles/jqx.base.css" rel="stylesheet" type="text/css">
<link href="scripts/jqwidgets/styles/jqx.classic.css" rel="stylesheet" type="text/css">
<script src="scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxcore.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxbuttons.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxscrollbar.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxdata.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxlistbox.js" type="text/javascript"></script>
</head>
<body>
<div id="jqxlistbox"></div>
<script type="text/javascript">
var string;
$(document).ready(function() {
// prepare the data
var source =
{
datatype: "json",
datafields: [
{name: 'firstname'},
{name: 'lastname'}
],
url: 'my url is here'
};
string = source.datafields[0] + source.datafields[1];
alert(string);
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxlistbox").jqxListBox(
{
source: dataAdapter,
theme: 'classic',
width: 200,
height: 250,
displayMember: 'string',
valueMember: 'firstname'
});
});
</script>
</body>
</html>
I think that the "beforeLoadComplete" callback of the jqxDataAdapter plug-in will help you to customize the loaded data through the plug-in. For more information about that function, please look at: jqxDataAdapter plug-in

Function this.text=text; to html

I have some code for a tootlip in a calendar. i want to be able to display html in the tool tip is this possible? every time i try and change it to accept html it crashes it only allows text right now and i do not understand how to change it to allow for html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script type='text/javascript' src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<style type='text/css'>
.pink > a {
background-color: pink !important;
background-image:none !important;
}
.green > a {
background-color: green !important;
background-image: none !important;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var Event = function(text, className) {
// would like to convert this to allow for html
this.text = text;
// this.html = text; // does not work
this.className = className;
};
var events = {};
events[new Date("01/01/2013")] = new Event("New Years Day", "pink");
events[new Date("12/25/2012")] = new Event("<B>Merry</b> Christmas", "green");
console.dir(events);
$("#dates").datepicker({
beforeShowDay: function(date) {
var event = events[date];
if (event) {
return [true, event.className, event.text];
}
else {
return [true, '', ''];
}
}
});
});//]]>
</script>
</head>
<body>
<div id="dates"></div>
</body>
</html>
thank you in advance for any code or help you may provide
Johnny
The title attribute does not allow html code.
But there are several frameworks out there that allow you to modify the hover.
I used jQuery Tooltip
<script src="http://jquery.bassistance.de/tooltip/jquery.tooltip.js"></script>
$('*').tooltip();
Here you will see that they tooltip has been modified and the bold is in place.
http://jsfiddle.net/Morlock0821/WqrMK/

Saving Changes in SlickGrid with php

I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:
Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');
$data = '';
$i = 0;
$query = "
SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$data .= '
data['.$i.'] = {
id: "'.$row['id'].'",
title: "'.$row['title'].'",
duration: "'.$row['duration'].'",
percentComplete: "'.$row['percentComplete'].'",
start: "'.$row['start'].'",
finish: "'.$row['finish'].'",
effortDriven: "'.$row['effortDriven'].'"
};
';
$i++;
echo $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<?php // include("includes/cms_head_scripts.php"); ?>
<link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" src="js/jquery.json.js"></script>
</head>
<body>
<div id="content_cont">
<div id="main">
<div style="position:relative">
<div style="width:600px;">
<div id="myGrid" style="width:100%;height:500px;"></div>
</div>
</div>
pricing
</div><!-- #main -->
</div><!-- #content_cont -->
<script src="lib/firebugx.js"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js"></script>
<script src="lib/jquery.event.drag-2.0.min.js"></script>
<script src="slick.core.js"></script>
<script src="plugins/slick.cellrangeselector.js"></script>
<script src="plugins/slick.cellselectionmodel.js"></script>
<script src="slick.editors.js"></script>
<script src="slick.grid.js"></script>
<script type="text/javascript">
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title", editor:TextCellEditor},
{id:"duration", name:"Duration", field:"duration", editor:TextCellEditor},
{id:"%", name:"% Complete", field:"percentComplete", editor:TextCellEditor},
{id:"start", name:"Start", field:"start", editor:TextCellEditor},
{id:"finish", name:"Finish", field:"finish", editor:TextCellEditor},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven", editor:TextCellEditor}
];
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true
};
$(function() {
<?php echo $data ?>
grid = new Slick.Grid($("#myGrid"), data, columns, options);
})
</script>
<form method="POST" action="save_price.php">
<input type="submit" value="Save">
<input type="hidden" name="data" value="">
</form>
<script type="text/javascript">
$(function() {
$("form").submit(
function() {
$("input[name='data']").val($.JSON.encode(data));
}
);
});
</script>
</body>
</html>

Categories