I'm Trying to create a bar chart using Highcharts for my Codeigniter project
Created Controller, View & Model with relevant Routes
tbl_demo_viewer table:
CREATE TABLE IF NOT EXISTS `tbl_demo_viewer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`numberofview` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
tbl_demo_click table:
CREATE TABLE IF NOT EXISTS `tbl_demo_click` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`numberofclick` int(12) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
application/config/database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'h_sole',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
application/config/routes.php
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['my-chart'] = "Chart";
application/controllers/Chart.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Chart extends FZ_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Chart_model');
}
public function createChart()
{
$this->data['click'] = $this->Chart_model->getClick();
$this->data['viewer'] = $this->Chart_model->getViewer();
$bc = array(array('link' => base_url(), 'page' => 'Home'), array('link' => '#', 'page' => 'Demo'));
$meta = array('page_title' => 'Demo', 'bc' => $bc);
$this->render('my_chart', $meta, $this->data);
}
}
application/models/Chart_model.php
<?php
class Chart_model extends CI_Model {
function __construct() {
parent::__construct();
}
public function getViewer() {
$this->db->set_dbprefix('');
$this->db->select('SUM(numberofview) as count');
$this->db->from('tbl_demo_viewer');
$this->db->group_by('tbl_demo_viewer.created_at');
$this->db->order_by('tbl_demo_viewer.created_at');
$q = $this->db->get();
}
public function getClick() {
$this->db->set_dbprefix('');
$this->db->select('SUM(numberofclick) as count');
$this->db->from('tbl_demo_click');
$this->db->group_by('tbl_demo_click.created_at');
$this->db->order_by('tbl_demo_click.created_at');
$q = $this->db->get();
}
}
application/views/my_chart.php
<!DOCTYPE html>
<html>
<head>
<title>HighChart</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
var data_click = <?php echo $click; ?>;
var data_viewer = <?php echo $viewer; ?>;
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Yearly Website Ratio'
},
xAxis: {
categories: ['2013','2014','2015', '2016']
},
yAxis: {
title: {
text: 'Rate'
}
},
series: [{
name: 'Click',
data: data_click
}, {
name: 'View',
data: data_viewer
}]
});
});
</script>
<div class="container">
<br/>
<h2 class="text-center">Codeigniter 3 - Highcharts mysql json example</h2>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Chart Example</div>
<div class="panel-body">
<div id="container"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
No error fired. But did not created the desired chart. I can not understand what I am going wrong. Can anyone help me ?
Related
I'm trying to use the Advanced Custom Field (ACF) plugin to return JSON via ajax in WordPress.
The below code correctly returns the JSON data of the posts but is not giving me the ACF data inside each post.
How can I get that ACF data into JSON?
PHP File
add_shortcode("owt-ajax-shortcode", "owt_wpl_run_shortcode");
function owt_wpl_run_shortcode() {
ob_start();
include_once plugin_dir_path(__FILE__) . 'views/owt-ajax-page-view.php';
$template = ob_get_contents();
ob_end_clean();
echo $template;
}
add_action("wp_enqueue_scripts", "owt_include_scripts");
function owt_include_scripts() {
wp_enqueue_script("jquery");
}
add_action("wp_ajax_owt_ajax_lib", "owt_lib_ajax_handler_fn");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_lib_ajax_handler_fn");
function owt_lib_ajax_handler_fn() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$all_posts = get_posts(array(
"post_type" => "post",
"post_status" => "publish",
'posts_per_page' => 20,
'order' => 'DESC',
'orderby' => 'date',
'cat' => 66
));
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $all_posts );
die;
}
}
wp_die();
}
JavaScript
<button id="btn-get-all-posts">Click to get All Posts</button>
<script>
jQuery(function () {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery("#btn-get-all-posts").on("click", function () {
var postdata = "action=owt_ajax_lib¶m=get_all_posts";
jQuery.post(ajaxurl, postdata, function (response) {
console.log(response);
});
});
});
</script>
instead of use get_posts try your own query with WP_Query
here is an example code, please let me know if it works correctly(I didn't test it yet)
function owt_lib_ajax_handler_fn()
{
$param = isset($_REQUEST[ 'param' ]) ? trim($_REQUEST[ 'param' ]) : "";
if ( ! empty($param) ){
if ( $param == "get_all_posts" ){
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 66 ],
];
$all_posts = new WP_Query($args);
$json_response = [];
if ( $all_posts->have_posts() ){
while ( $all_posts->have_posts() ) {
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields(get_the_ID()),
],
];
}
wp_send_json($json_response, 200);
wp_die();
}
else {
wp_send_json($json_response, 404);
wp_die();
}
}
}
wp_die();
}
please have a look as below:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => array('red', 'orange'),
'compare' => 'IN',
),
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
),
));
Please use below function:
add_action("wp_ajax_owt_ajax_lib", "owt_ajax_lib");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_ajax_lib");
function owt_ajax_lib() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 33 ],
];
$all_posts = new WP_Query($args);
$json_response = array();
if ( $all_posts->have_posts() ):
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields( get_the_ID() ),
],
];
endwhile;
endif;
echo json_encode($json_response);
die;
}
}
die;
}
I want to send email using codeignator mails are sending properly but not saving in send folder i have put code below.
public function sendMail()
{
$data=array('fromEmail'=>'xyz#gmail.com','to'=>'abc#gmail.com','cc'=>'','subject'=>'Login Count','template'=>"Any msg");
$localhost = array(
'127.0.0.1',
'::1'
);
$this->load->library('email');
$config = Array(
/*'charset'=>'utf-8',
'wordwrap'=> TRUE,
'mailtype' => 'html'*/
'mailtype' => 'html',
'priority' => '3',
'charset' => 'iso-8859-1',
'validate' => TRUE ,
'newline' => "\r\n",
'wordwrap' => TRUE
);
if(in_array($_SERVER['REMOTE_ADDR'], $localhost))
{
$config['protocol']='smtp';
$config['smtp_host']='ssl://smtp.office365.com';
$config['smtp_port']='465';
$config['smtp_user']='xyz#gmail.com';
$config['smtp_pass']='****';
$config['mailtype']='html';
}
$this->email->initialize($config);
/*if(isset($data['fromEmail']) && $data['fromEmail']!='')
{
$fromEmail = $this->getValue($this->db->dbprefix('admin_users'),"email"," `id` = '1' ");
}*/
$fromName = 'Creosouls Team';
$this->email->clear(TRUE);
$this->email->to($data['to']);
if(isset($data['cc']) && $data['cc'] !='')
{
$this->email->cc($data['cc']);
}
$this->email->from($data['fromEmail'],$fromName);
$this->email->subject($data['subject']);
$this->email->message($data['template']);
$this->email->send();
echo $this->email->print_debugger();
pr($data);
// if($this->email->send())
// return true;
// else
// return false;
}
I have a dynamically loaded dropdownlist called type_id, and I would like that when I select a value in that dropdownlist, my description textarea field would be updated with a value.
form
echo $form->field($model, 'type_id')->dropDownList(ArrayHelper::map($types,'id','name'),['prompt'=>'Selecione a Área',
'onchange' => '???']);
<?= $form->field($model, 'description')->textarea(['rows' => 8]) ?>
This value will be obtained dynamically through the query:
Controller
public function actionScript($id)
{
$types = Type::find()
->where(['id' => $id])
->One();
return $type->script;
}
That is, in textarea field I want to show the respective script column to the selected id in type_id dropdonw.
type table
TABLE `mod_helpdesk_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`priority` int(1) NOT NULL DEFAULT '0',
`script` text NOT NULL,
`active` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
It will help you
echo $form->field($model, 'type_id')->dropDownList(ArrayHelper::map($types,'id','name'),['prompt'=>'Selecione a Área',
['class' => 'your_class', 'id' => 'your_id']
'onchange' => '???']);
<?= $form->field($model, 'description')->textarea(['rows' => 8,'id'=>'textArea']) ?>
$('#your_id').change(function(){
$('#textArea').val('testing');
})
try onchange ajax event
echo $form->field($model, 'type_id')->dropDownList(ArrayHelper::map($types,'id','name'),[
'prompt'=>'Selecione a Área',
'onchange' => '
$.get( "yourControllerName/script&id="+$(this).val(), function( data ) {
$( "#yourTextAreaIdElement" ).val( data );
});
'
]);
and better prevent if request has an ids passed into actionScript
public function actionScript($id)
{
$script = '';
if(!empty($id)) {
$types = Type::find()
->where(['id' => $id])
->one();
if(!empty($types)) {
$script = $types->script;
}
}
return $script;
}
Like that?
$('#<?php echo Html::getInputId($model, 'type_id'); ?>').change(function () {
var val = $(this).val();
$.ajax({
url: '<?php echo Url::to('script'); ?>',
type: 'get',
data: {id: val},
success: function (data) {
$('#<?php echo Html::getInputId($model, 'description'); ?>').val(data);
}
});
});
I am updating an existing CI project on an AWS Ubuntu 12/PHP 4.2/CI 1.3.1 to a new AWS instance running Ubuntu 16.0.4 LTS/Apache 2.4.18/PHP 7.0.8/MySQL 5.7.15/CI 3.1.0.
I can connect and select data from mysql command line using the settings in database.php I wrote a non-CI test PHP page that also returns correct results. The same query in the model returns 0 results.
I've been tweaking the settings trying to get this to work. This is the current snapshot of database.php.
$active_group = 'default';
$query_builder = TRUE;
// 'db_debug' => (ENVIRONMENT !== 'production'),
$db['default'] = array(
'dsn' => '',
'hostname' => '127.0.0.1',
'username' => '****',
'password' => '****',
'database' => '****',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => FALSE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Here is the applicable section of the model:
class User_model extends CI_Model
{
function __construct()
{
parent::__construct();
log_message("info","User_model class instantiated");
}
... section omitted ...
function login($username, $password)
{
$this->load->library('encrypt');
// Get the hash of the entered password to lookup in the database
//$password_hash = $this->encrypt->sha1($password); (Removed 10/8/2016 ES SHA1 deprecated)
$newpassword_hash = $this->encrypt->encode($password);
$this->db->where('user_name', $username );
$this->db->or_where('email', $username);
$query = $this->db->get('users', 1);
if($query->num_rows == 0){
log_message("info","User not found");
return false;
}
else
{
... remainder omitted ...
var_dump($this->db->last_query());
string(107) "SELECT * FROM `users` WHERE `user_name` = 'xxxxxx#gmail.com' OR `email` = 'xxxxxx#gmail.com' LIMIT 1"
var_dump($query);
object(CI_DB_mysqli_result)#23 (8) { ["conn_id"]=> object(mysqli)#15 (19) { ["affected_rows"]=> int(1) ["client_info"]=> string(79) "mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $" ["client_version"]=> int(50012) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(60) ["host_info"]=> string(20) "127.0.0.1 via TCP/IP" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(23) "5.7.15-0ubuntu0.16.04.1" ["server_version"]=> int(50715) ["stat"]=> string(138) "Uptime: 229367 Threads: 7 Questions: 1083 Slow queries: 0 Opens: 440 Flush tables: 1 Open tables: 241 Queries per second avg: 0.004" ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(223) ["warning_count"]=> int(0) } ["result_id"]=> object(mysqli_result)#22 (5) { ["current_field"]=> int(0) ["field_count"]=> int(60) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) } ["result_array"]=> array(0) { } ["result_object"]=> array(0) { } ["custom_result_object"]=> array(0) { } ["current_row"]=> int(0) ["num_rows"]=> NULL ["row_data"]=> NULL }
if you use $query = $this->db->get('users', 1); this format to query in CI
then the number of rows will be achieved by as following:
$this->db->where('user_name', $username );
$this->db->or_where('email', $username);
$query = $this->db->get('users')->result_array();
if(count($query) == 0){
log_message("info","User not found");
return false;
}
else{
//do what you want
}
otherwise you can use like the following:
$query = $this->db->query('your sql here');
if($query->num_rows == 0){
log_message("info","User not found");
return false;
}
else{
//do what you want
}
Hope this may solve your problem.:)
I have create a action comment like this:
public function actionComment($id)
{
$text = CommentModel::find($id)->where(true)->all();
if (isset($_POST['name'])) {
$text = new CommentModel();
$text->name=$_POST['name'];
$text->comment=$_POST['comment'];
$text->i_post=$_POST['id_post'];
$text->save();
$this->redirect('comment',array('id'=>$text->id));
}
return $this->render('comment',array("text"=>$text));
}
and comment view is:
<h2>List of all comments:</h2>
<?php
foreach($text as $text[0]){
echo "name"." ".":"." ".$text[0]->name."<br>" ;
echo "comment"." ".":"." ".$text[0]->comment."<br>";
?>
my comment model is:
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'comment' => 'Comment',
'id-post' => 'Id Post',
];
}
how should i define id_pst in my project to each post has sepecific comment??