Creating a PHP json feed and successfully linking it to javascript - javascript

I have a project i am working on that requires sending information from database through a php script using json feed to javascript. Here are the scripts:
This is the javascript:
<link rel= 'stylesheet' type='text/css' href='fullcalendar/fullcalendar/fullcalendar.css' />
<link rel="stylesheet" media="print" href="fullcalendar/fullcalendar/fullcalendar.print.css" />
<script type="text/javascript" src="fullcalendar/lib/jquery.min.js"></script>
<script type='text/javascript' src="fullcalendar/fullcalendar/fullcalendar.js"></script>
<script type="text/javascript" src="fullcalendar/lib/jquery-ui.custom.min.js" ></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: "public_calendar.php"
})
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
?php require_once("includes/initialize.php"); ?>
<?php require_once(LIB_PATH.DS.'database.php'); ?>
<?php
//Find all the events
$events = Event::find_all();
foreach($events as $event):
$id = (int) $event->id;
$title = "{$event->event_title}";
$start = "{$event->start_date}" ." ". "{$event->start_time}";
$end = "{$event->end_date}" ." ". "{$event->end_time}";
$url = "event_detail.php";
echo json_encode( array(
'id' => $id,
'title' => "{$title}",
'start' => "{$start}",
'end' => "{$end}",
'url' => "{$url}"
));
endforeach;
?>
This is how the php script should look like:
[ {"id":111,"title":"Event1","start":"2013-10-10","url":"http:\/\/yahoo.com\/"},
{"id":222,"title":"Event2","start":"2013-10-20","end":"2013-10-22","url":"http:\/\/yahoo.com\/"}
]
This is how it looks like now:
{"id":12,"title":"Matriculation","start":"2013-11-5 08:00","end":"2013-11-5 17:00","url":"event_detail.php"}
{"id":13,"title":"Exam","start":"2013-11-30 09:00","end":"2013-11-30 16:00","url":"event_detail.php"}
{"id":2,"title":"Convocation","start":"2013-12-11 08:00","end":"2013-12-11 19:00","url":"event_detail.php"}
Thanks for your help in advance.

The best way to achieve the result you want is to create an array in PHP, then use json_encode() to create the output. You're already doing some of this - you just need a little more:
<?php
//Find all the events
$events = Event::find_all();
$eventList = array(); // Assemble list of all events here
foreach($events as $event):
$eventList[] = array( // Add our event as the next element in the event list
'id' => (int) $event->id,
'title' => $event->event_title,
'start' => $event->start_date." ".$event->start_time,
'end' => $event->end_date." ".$event->end_time,
'url' => "event_detail.php"
);
endforeach;
echo json_encode($eventList); // encode and output the whole list.
?>
I've also simplified and shortened some of your code to remove the unnecessary double quotes.

Related

Running JS-File in php

I’ve a questionnaire that I analyze with php. The data are supposed to be displayed in a Java-based polar-graph and a table.
You can see how it looks with static data here.
However, the graph doesn’t show when I use the data from my database. The table works fine. A few days ago I asked about how to integrate php-data to java via json_encode because I thought this might be the problem, but I learned (thanks again) that this is the correct approach.
My web-hoster says that it doesn’t support php in html, so I modified the index.html to an index.php. I have no idea what to modify to make it work. Database-connection works, php-values in the table are correct, the js-graph works fine with static data.
Here are my php-arrays:
$arr1 = array(axis => "Gesundheitszustand", value => $X1P);
$arr2 = array(axis => "BMI", value => $X3);
$arr3 = array(axis => "Stress", value => $X10P);
$arr4 = array(axis => "Körperliche Aktivität", value => $X4P);
$arr5 = array(axis => "Nahrung: Gemüse/Obst", value => $X8d);
$arr6 = array(axis => "Nahrung: Fisch", value => $X8f);
$arr7 = array(axis => "Nahrung: Fleisch", value => $X8h);
$arr8 = array(axis => "Geistige Gesundheit", value => $X9P);
$arr9 = array(axis => "Zufriedenheit", value => $X2P);
$arr10 = array(axis => "Rauchen", value => $X9a);
The values are numbers between 0 and 1.
That’s how I try to include the js-file in my php-file:
<html>
<head>
<script src="d3js.js"></script>
<script src="radarchart.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php ?>
<script type="text/javascript" src="script.js"></script>
<?php ?>
</body>
And that’s how I include my php-data to the js-file:
var d = [
[
<?php echo json_encode($arr1); ?>,
<?php echo json_encode($arr2); ?>,
<?php echo json_encode($arr3); ?>,
<?php echo json_encode($arr4); ?>,
<?php echo json_encode($arr5); ?>,
<?php echo json_encode($arr6); ?>,
<?php echo json_encode($arr7); ?>,
<?php echo json_encode($arr8); ?>,
<?php echo json_encode($arr9); ?>,
<?php echo json_encode($arr10); ?>,
],[
{axis:"Gesundheitszustand",value:0.63},
{axis:"BMI",value:0.58},
{axis:"Stress",value:0.67},
{axis:"Körperliche Aktivität",value:0.33},
{axis:"Nahrung: Gemüse/Obst",value:0.66},
{axis:"Nahrung: Fisch",value:0.25},
{axis:"Nahrung: Fleisch",value:0.50},
{axis:"Geistige Gesundheit",value:0.68},
{axis:"Zufriedenheit",value:0.7},
{axis:"Rauchen",value:0.91},
]
];
Although json_encode is the correct way, it has to be the data-integration, correct? Or am I missing something?
Any suggestions? Many thanks for your comments/help in advance!
Use echo to output a string directly

Javascript call php function and receives back results

This postprovides sample code using obtaining a server file list as an example. Here is the code I have used:
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>How to create form using jQuery UI</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/pepper-grinder/jquery-ui.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.get('getfilename.php', { dir : '/ajax1/' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
alert ("ok");
});
</script>
</head>
<body>
<h1>Get file names... </h1>
</body>
</html>
getfilename.php
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
My problem is that the javascript alert alert('index ' + key + ' points to file ' + val); fails to display anything on the page. The script is working because I get a response in the Firebug console log.
ajax.jsajax.phpindex.html["ajax.js","ajax.php","index.html"]
What I need to change on the script to return this information to the html page so that I can use the JSON for further processing ?
Thanks.
With your debug you broke the JSON output in PHP. So, remove:
echo $filesArray[$Counter].'';
Also, before any output, you should add JSON header:
header('Content-Type: application/json');
At the end, your PHP file should look like this:
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[] = $file;
}
}
header('Content-Type: application/json');
echo json_encode($filesArray);

Cakephp 3.0 autocomplete jquery ui

I need to know why the following isnt working .This code will extract data from index controller to search get json data.Neither does any request is made and nothing happens
I'm new to both Cakephp 3.0
I'm trying to get an autocomplete / autosuggest working in CakePHP 3.0 but everything I find is either for 1.3 or not for Cake at all and I don't know what to do to get it working properly.I precisely need it for cakephp 3.0
snippet
1.CarsController.php
This is carscontroller accesses when an ajax request and will encode in json data
2.CarsTable.php
fetches data from the carstable
3.index.ctp
is the view page and autocomplete method
<?php
namespace App\Controller;
use App\Controller\AppController;
class CarsController extends AppController {
public function index() {
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax')) {
$term = $this->request->query('term');
$carNames = $this->Car->getCarNames($term);
$this->set(compact('carNames'));
$this->set('_serialize', 'carNames');
}
}
}
?>
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class Carstable extends AppModel {
public function getCarNames ($term = null) {
if(!empty($term)) {
$cars = $this->find('list', array(
'conditions' => array(
'name LIKE' => trim($term) . '%'
)
));
return $cars;
}
return false;
}
}
?>
<?php
//let's load jquery libs from google
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));
//load file for this view to work on 'autocomplete' field
//form with autocomplete class field
echo $this->Form->create();
echo $this->Form->input('name', array('class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->end();
?>
<script type="text/javascript">
(function($) {
$('#autocomplete').autocomplete({
source: "<?php (array('controller'=>'Cars','action'=>'search')); ?>",
datatype:"json",
minLength: 1
})
})
</script>
This code snippet will work for autocomplete in cakephp 3.0
View for search \Template\post\
Search.ctp
<?php
use Cake\Routing\Router;
use Cake\View\Helper\UrlHelper;
?><div class="ui-widget">
<?php
echo $this->Form->create('Posts', array('action' => 'search'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->end();
?></div><div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'<?php echo Router::url(array("controller" => "posts", "action" => "search")); ?>',
minLength: 1
}); });
</script>
In your controller add this function .Change database and other variable properly.
src\Controller\PostController.php
public function search()
{
if ($this->request->is('ajax')) {
$this->autoRender = false;
$name = $this->request->query('term');
$results = $this->Posts->find('all', array(
'conditions' => array('Posts.title LIKE ' => '%' . $name . '%')
));
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['title'] , 'value' => $result['title'] );
}
echo json_encode($resultArr);
}}
In routes.php add this line
Router::extensions('json', 'xml');

WordPress - Modify admin-header.php or use functions.php for inserting a jQuery script to header?

Im developing a Form with a (jQuery) onClick button so I can import results from other documents straight into WP Custom Fields.
To do this I MUST include this script to my Form:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
If I don't include this script then my Form wont work :(
And if I include this script then I can ADD NEW POST and use my Form + Button but then the EDIT POST page wont show up and I only see a WHITE SCREEN.
Finally I figured out if I insert this CODE to LINE 59 in admin-header.php:
<?php if ( is_admin() && $parent_file == 'edit.php') { ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php } ?>
Then everything will work 100% as I want :D
I thought WP already was using/including this script by default but this is NOT true as I can see. At least not for WP-Backend (Post page).
The problem is: I dont want to edit WP CORE files, so my question is how can I get the same result using functions.php instead of editing admin-header.php?
Just to show you how admin-header looks like from LINE 50 to LINE 73:
<title><?php echo $admin_title; ?></title>
<?php
wp_enqueue_style( 'colors' );
wp_enqueue_style( 'ie' );
wp_enqueue_script('utils');
$admin_body_class = preg_replace('/[^a-z0-9_-]+/i', '-', $hook_suffix);
?>
<?php if ( is_admin() && $parent_file == 'edit.php') { ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php } ?>
<script type="text/javascript">
addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>',
pagenow = '<?php echo $current_screen->id; ?>',
typenow = '<?php echo $current_screen->post_type; ?>',
adminpage = '<?php echo $admin_body_class; ?>',
thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>',
decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>',
isRtl = <?php echo (int) is_rtl(); ?>;
</script>
As you can se my CODE is on LINE 11,12 and 13 to make it work.
You can try something like this in your theme functions.php
function admin_add_script() {
wp_enqueue_script('jquery_script', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array(), null);
}
add_action('admin_head-edit.php', 'admin_add_script');
Try adding this to your functions.php:
<?php
function add_jquery_data() {
global $parent_file;
if ( isset( $_GET['action'] ) && $_GET['action'] == 'edit' && isset( $_GET['post'] ) && $parent_file == 'edit.php') {
echo "<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>";
}
}
add_filter('admin_head', 'add_jquery_data');
?>
I hope this helps.

passing information via javascript using php

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="./js/jquery.js"></script>
<script src="./js/laddubox.js"></script>
<script src="./js/pop.js"></script>
<script src="./js/jquery.js"></script>
<script type="text/javascript">
var sbs = {
'url' : '<?="./gearedup-pics/"?>',
'logged' : '<?=$notregister?>',
'userid' : '<?= $id ?>',
'father' : '<?= $father ?>' ,
'mother' : '<?= $mother ?>',
'kid' : "<?= $kid ?>"
};
</script>
<title><?=$title?></title>
</head>
I am sending information via javascript using php but $kid ,$mother and $father are in array format . So its showing me an error.
Notice: Array to string conversion in C:\xampp\htdocs\sbs\sbs\html\meta.php on line 19
Array' ,
<?= converts the variable to a string and outputs it. Implicitly converting arrays to strings results in a notice (not an error).
I advise you to use json_encode():
<?php
$data = array(
'url' => './gearedup-pics/',
'logged' => $notregister,
'userid' => $id,
'father' => $father,
'mother' => $mother,
'kid' => $kid
);
?>
var sbs = <?php echo json_encode($data); ?>;

Categories