how to display image from uploads folder in wordpress - image

I am just learning to create meta box to upload file in wp-content/uploads folder through below code:
//display image meta box
function display_image_box() {
global $post;
wp_nonce_field( plugin_basename( __FILE__ ), 'wp_custom_noncename' );
echo '<input id="post_media" type="file" name="post_media" value="" size="25" />';
}
//upload image
function update_custom_meta_data( $id, $data_key, $is_file = false ) {
global $post;
if( $is_file && ! empty( $_FILES ) ) {
$upload = wp_handle_upload( $_FILES[$data_key], array( 'test_form' => false ) );
if( isset( $upload['error'] ) && '0' != $upload['error'] ) {
wp_die( 'There was an error uploading your file. ' );
} else {
update_post_meta( $id, $data_key, $upload );
}
}
}
//save image
function save_custom_meta_data( $id ) {
if( ! wp_verify_nonce( $_POST['wp_custom_noncename'], plugin_basename( __FILE__ ) ) ) {
return;
}
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
update_custom_meta_data( $id, 'post_media', true );
}
add_action( 'save_post', 'save_custom_meta_data' );
//register script
function register_admin_scripts() {
wp_register_script( 'custom_admin_script', get_template_directory_uri() . '/js/admin.js' );
wp_enqueue_script( 'custom_admin_script' );
}
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
this working & uploaded file nicely but i cant display it cause getting the array something like this:
> [post_media] => Array
(
[0] => a:3:{s:4:"file";s:81:"E:wampwwwtestchild/wp-content/themes/twentyeleven/uploads/2012/12/coffee_star.jpg";s:3:"url";s:60:"wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg";s:4:"type";s:10:"image/jpeg";}
)
so how can i display the image file now ?

Since the custom fields are saved in _postmeta table, we will get it by $post->ID.
$media = stripslashes(get_post_meta($post->ID, 'post_media', true));
if (isset($media[0])){
echo '<img src="'.$media.'" alt="images" />';
}
Hope it helps...
And if you want to try this code.
Upload Script
<script type="text/javascript">
var formfield = '';
$j(document).ready(function(){uploadimagebutton();});
function uploadimagebutton() {
$j('#upload_image_button').click(function() {
formfield = $j(this).prev().attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
imgurl = $j(html).attr('src');
$j('#'+formfield).val(imgurl);
tb_remove();
$j('#pagebackgroundthumb').html('<img src="'+imgurl+'" alt="" style="max-width:85%;" />');
} else {
window.original_send_to_editor(html);
}
};
$j('#delete_image_button').click(function(){
formfield = $j(this).prev().prev().attr('name');
$j('#'+formfield).attr('value', '');
$j('#pagebackgroundthumb').html('');
});
}
</script>
place this in your theme function.php
<?php
/* -------------------------------------------------------------
Meta boxes
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
add_action('edit_post', 'adj_update');
add_action('save_post', 'adj_update');
add_action('publish_post', 'adj_update');
/* Use the admin_menu action to define the custom boxes */
add_action('admin_menu', 'adj_add_custom_box');
/* Adds a custom section to the "advanced" Post and Page edit screens */
function adj_add_custom_box() {
if( function_exists( 'add_meta_box' )) {
add_meta_box( 'addsettings', 'Additional Settings',
'adj_inner_custom_box', 'page', 'advanced', 'high' );
}
}
/* Prints the inner fields for the custom post/page section */
function adj_inner_custom_box() {
// Use nonce for verification
echo '<input type="hidden" name="myplugin_noncename" id="myplugin_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// The actual fields for data entry
global $post;
$subtitle = stripslashes(get_post_meta($post->ID, 'subtitle', true));
$pagebackground = stripslashes(get_post_meta($post->ID, 'pagebackground', true));
?>
<div class="inside">
<label for="subtitle"><strong>Page Subtitle:</strong> </label>
<input type="text" name="subtitle" value="<?php echo $subtitle ?>" id="subtitle" style="width:95%" />
<p>If menu title is different with page title, please type here the desired page title.</p>
<label for="pagebackgroundthumb"><strong>Page Background Image:</strong> </label>
<div id="pagebackgroundthumb"><?php if(!empty($pagebackground))echo '<img src="'.$pagebackground.'" alt="" width="80%" />';?></div>
<input id="upload_image" name="pagebackground" type="hidden" size="45" value="<?php echo $pagebackground;?>">
<input class="button-secondary" id="upload_image_button" value="Upload/Select an image" type="button"><input class="button-secondary" id="delete_image_button" value="Delete" type="button">
</div>
<?php
}
function adj_update($id) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
return $post_id;
}
$label = $_POST['subtitle'];
$pagebackground = $_POST['pagebackground'];
if (!empty($label)) {
$meta_value = get_post_meta($id, 'subtitle', true);
if(!empty($meta_value)) {
update_post_meta($id, 'subtitle', $label);
} else {
add_post_meta($id, 'subtitle', $label, true);
}
} else {
delete_post_meta($id, 'subtitle');
}
if (!empty($pagebackground)) {
$meta_value = get_post_meta($id, 'pagebackground', true);
if(!empty($meta_value)) {
update_post_meta($id, 'pagebackground', $pagebackground);
} else {
add_post_meta($id, 'pagebackground', $pagebackground, true);
}
} else {
delete_post_meta($id, 'pagebackground');
}
}
?>

Related

ACF field for Tribe events category

I have ACF field for Tribe events category.
Can't find the solution for showing the field in Tribe events template. This is my code below:
<?php
$event_id = get_the_ID();
$event_cats = get_the_terms($event_id, 'tribe_events_cat');
$custom_field = get_field( 'custom_field', Tribe__Events__Main::TAXONOMY );
foreach ($event_cats as $category) {
echo '<p>' . $category->name . '</p>';
echo '<p>' . $custom_field . '</p>';
}
?>
UPDATE===
Add a function to functions.php
if ( class_exists('Tribe__Events__Main') ){
function tribe_get_color_categories ( $event_id = null ) {
if ( is_null( $event_id ) ) {
$event_id = get_the_ID();
}
$event_cats = '';
$term_list = wp_get_post_terms( $event_id, Tribe__Events__Main::TAXONOMY );
foreach( $term_list as $term_single ) {
$category_color_primary = get_field('event_category_color', $term_single);
}
if($category_color_primary) {
echo 'style="color:';
echo $category_color_primary;
echo ' " ';
}
}
}
And then call it on the template
<div <?php echo tribe_get_color_categories (); ?>>Some text</div>

Add to cart ajax custom product type options

I am trying to add custom product type to product like here wild card
and i succeeded but now i have to add this value to cart with ajax how i suppose to do this with drop-down and shortcode? i just added load_book.js but didn't added any script code because i don't know how to write ajax code for this. thanks.
My code:
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_filter("product_type_options", "woo_bookable_product");
function woo_bookable_product($product_type_options)
{
$product_type_options["Bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => "Bookable",
"description" => "Book Your Product",
"default" => "yes",
);
return $product_type_options;
}
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"] ? 'yes' : 'no';
update_post_meta($product->ID, "_bookable" ,$meta_value);
}
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts','woo_bookable_scripts');
add_action('wp_ajax_woo_bookable_shortcode', 'woo_bookable_shortcode');
add_action('wp_ajax_nopriv_woo_bookable_shortcode', 'woo_bookable_shortcode');
function woo_bookable_shortcode()
{
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable'
));
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
add_shortcode('bookable','woo_bookable_shortcode');
Finally find the solution
PHP:
<?php
/**
* Plugin Name: Bookable
* Description: Add shortcode [bookable] or in php - echo do_shortcode('[bookable]');
* Version: 0.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) ){
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter("product_type_options", "woo_bookable_product");
if(!function_exists('woo_bookable_product')):
function woo_bookable_product($product_type_options)
{
$product_type_options["bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => __("Bookable",'woocommerce'),
"description" => __("Check if product is bookable or not",'woocommerce'),
"default" => "no",
);
return $product_type_options;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_add_cart_item_data', 'woo_bookable_custom_field', 10, 2 );
if(!function_exists('woo_bookable_custom_field')):
function woo_bookable_custom_field( $cart_item_data, $product_id )
{
$get_custom_meta = get_post_meta( $product_id , '_bookable', true );
if( $get_custom_meta == 'yes' )
{
$cart_item_data[ '_bookable' ] = $get_custom_meta;
$len = 10;
$word = array_merge(range('a', 'z'), range('A', 'Z'));
$name = shuffle($word);
$name = substr(implode($word), 0, $len);
$cart_item_data['unique_key'] = $name ;
}
return $cart_item_data;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter( 'woocommerce_get_item_data', 'render_woo_bookable_meta_data', 10, 2 );
if(!function_exists('render_woo_bookable_meta_data')):
function render_woo_bookable_meta_data( $cart_data, $cart_item )
{
global $woocommerce;
$custom_items = array();
if( !empty( $cart_data ) )
{
$custom_items = $cart_data;
}
if( isset( $cart_item['_bookable'] ) )
{
$custom_items[] = array(
"name" => __( "Bookable", "woocommerce" ),
"value" => $cart_item['_bookable'] );
$custom_items[] = array(
"name" => __( $cart_item['unique_key'], "woocommerce" ),
"value" => '$10' );
}
return $custom_items;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
if(!function_exists('add_custom_price')):
function add_custom_price( $cart_object )
{
foreach ( $cart_object->get_cart() as $hash => $value )
{
if($value['_bookable'] && $value['data']->is_on_sale())
{
$newprice = $value['data']->get_sale_price()+10;
$value['data']->set_price( $newprice );
}
elseif($value['_bookable'])
{
$not_sell = $value['data']->get_regular_price()+10;
$value['data']->set_price( $not_sell );
}
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_cart_calculate_fees', 'woo_bookable_cart_calculate_totals', 10, 1 );
if(!function_exists('woo_bookable_cart_calculate_totals')):
function woo_bookable_cart_calculate_totals( $cart_object )
{
$get_price = 0;
foreach ( $cart_object->get_cart() as $hash => $value )
{
if(!empty($value['_bookable']))
{
$percent = 10;
$get_price += $value['line_total'];
$fee = ($get_price * $percent) / 100;
}
}
$cart_object->add_fee( __("Bookable Charge($percent%)"),$fee ,false );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
if(!function_exists('woo_save_bookable_data')):
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"];
if(isset($meta_value))
{
$meta_value = 'yes';
update_post_meta( $product->ID, "_bookable" ,$meta_value );
wp_set_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
else
{
delete_post_meta($product->ID, "_bookable");
wp_remove_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('woocommerce_add_order_item_meta','woo_bookable_add_order_meta', 9, 3 );
if(!function_exists('woo_bookable_add_order_meta')):
function woo_bookable_add_order_meta( $item_id, $item_values, $item_key )
{
if( ! empty( $item_values['_bookable'] ) )
wc_update_order_item_meta( $item_id, '_bookable', sanitize_text_field( $item_values['_bookable'] ) );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
add_action( 'admin_notices', 'woo_bookable_active' );
if(!function_exists('woo_bookable_active')):
function woo_bookable_active()
{
$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
?>
<div class="error notice">
<p><?php echo sprintf("Please Activate or <a href='%s'>Install Woocommerce</a> to use Bookable plugin",$err_text); ?></p>
</div>
<?php
//If woocommerce is not installed deactive plugin
if (is_plugin_active('bookable/bookable.php')) {
deactivate_plugins(plugin_basename(__FILE__));
}
unset($_GET['activate']);
}
endif;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('wp_enqueue_scripts','woo_bookable_scripts');
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_shortcode('bookable','woo_bookable_shortcode');
function woo_bookable_shortcode()
{
global $product;
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable',
'meta_value' => 'yes'
) );
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$InArray = array('woo_bookable_product_id','woo_bookable_add_to_cart');
foreach($InArray as $SingleValue)
{
add_action('wp_ajax_'.$SingleValue,$SingleValue);
add_action('wp_ajax_nopriv_'.$SingleValue,$SingleValue);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_product_id()
{
$product_id = $_POST['product_id'];
if($product_id != null && $product_id!=0)
{
$add['id'] = 'success';
$add['msg'] = 'View Cart';
WC()->cart->add_to_cart( $product_id);
}
else
{
$add['id'] = 'fail';
$add['msg'] = 'Please Select Product From DropDown!!';
}
echo json_encode($add);
die();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_add_to_cart()
{
return '<button type="submit" style="margin-left:10px" name="add-to-cart" value="" class="single_add_to_cart_button button alt">Add To Cart</button>
<div class="message"></div>';
die();
}
ajax Script:
jQuery(document).ready(function()
{
jQuery("select.woo_book_pro").change(function(e)
{
var id = jQuery('.woo_book_pro option:selected').val();
var action = 'woo_bookable_add_to_cart';
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"id":id
},
success: function(data)
{
jQuery('.single_add_to_cart_button').attr('value',id);
jQuery('.single_add_to_cart_button').attr("disabled", "disabled");
jQuery('.single_add_to_cart_button').text('WAIT...');
setTimeout(function() {
jQuery('.single_add_to_cart_button').removeAttr("disabled");
jQuery('.single_add_to_cart_button').text('Add To Cart');
}, 3000);
}
});
});
jQuery(".single_add_to_cart_button").click(function(e) {
e.preventDefault();
var product_id = jQuery(this).val();
var action = 'woo_bookable_product_id';
jQuery('.message').empty();
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"product_id":product_id
},
success: function(data)
{
if(data.id == 'success')
{
jQuery('.message').prepend(data.msg);
return false;
}
if(data.id == 'fail')
{
jQuery('.message').prepend(data.msg).css('color','#F33')
return false;
}
}
});
});
});

Wordpress Ajax pagination returning 0 after second time

I am attempting to paginate my posts with an ajax.
I set an attribute "data-page" to the page link and extract it with jQuery to pass it with Ajax.
The first time a click on the link everything works fine but then if I click on a different link the ajax call returns 0.
Here's my code in my functions.php:
wp_register_script('load_post_ajax', get_template_directory_uri() . '/includes/ajax/load_post_ajax.js',array( 'jquery' ), 1.1, true);
$php_array = array( 'admin_ajax' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'load_post_ajax', 'php_array', $php_array );
wp_enqueue_script( 'load_post_ajax' );
/*
* PAGINATION
*/
function hs_pagination($pages = '', $range = 4)
{
$showitems = ($range * 2)+1;
if(isset($_POST['paged'])){
$paged = $_POST['paged'];
}else{
$paged = get_query_var( 'paged', 1 );
}
if(empty($paged)) $paged = 1;
if($pages == '')
{
global $wp_query;
$pages = $wp_query->max_num_pages;
if(!$pages)
{
$pages = 1;
}
}
if(1 != $pages)
{
echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages." </span>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."' data-page=1>« First</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹ Previous</a>";
for ($i=1; $i <= $pages; $i++)
{
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<a href=\"#\" class=\"current\" data-page=$i>".$i."</a>":"<a href='".get_pagenum_link($i)."' class=\"inactive\" data-page=$i>".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\" data-page=$paged + 1>Next ›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."' data-page=$pages>Last »</a>";
echo "</div>\n";
}
}
/*
* AJAX POSTS LOADER
*/
add_action( 'wp_ajax_load_post_ajax', 'load_post_ajax_init' );
add_action( 'wp_ajax_nopriv_load_post_ajax', 'load_post_ajax_init' );
function load_post_ajax_init() {
$total_posts_per_page = get_option('posts_per_page');
if($_POST['paged']){
$paged = $_POST['paged'];
}else{
$paged = get_query_var( 'paged', 1 );
}
$args = array(
'posts_per_page' => $total_posts_per_page,
'paged' => $paged,
'post_type' => 'post'
);
$posts = query_posts($args);
if($posts){
$count =0;
foreach($posts as $post){
?>
<article class="post">
<?php
if($paged < 2){
if(has_post_thumbnail($post->ID) ){
the_post_thumbnail($post->ID,'big',array('class'=>'img-responsive center-block'));
}else{
echo "no thumb";
}
}else{
echo "not first post";
}
?>
<p class="post_info hs_color"><?php echo $post->post_title . " Posted on: " . $post->post_date . " Author: ". get_the_author_meta( 'display_name',$post->post_author );?></p>
<p><?php echo $post->post_content;?></p>
<div class="post_link clearfix">
<a href="<?php the_permalink($post->ID);?>">
<h6 class="text-uppercase text-center">Read more</h6>
<div class="hs_square hs_square_right hs_bg"></div>
</a>
</div>
</article>
<?php
$count++;
}
}else {
echo "no posts found";
}
//PAGINATION
hs_pagination();
//PAGINATION
}
/*
*AJAx CALL
*/
jQuery( document ).ready(function() {
$('#post-section .container .pagination a').on('click',function(e){
/** Prevent Default Behaviour */
e.preventDefault();
var page = $(this).attr('data-page');
/** Ajax Call */
$.ajax({
cache: false,
timeout: 8000,
url: php_array.admin_ajax,
type: "POST",
data: ({
action:'load_post_ajax',
paged:page,
}),
beforeSend: function() {
},
success: function( data,response ){
$( '#post-section .container' ).addClass('animated FadeIn');
$( '#post-section .container' ).html( data);
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( 'The following error occured: ' + textStatus, errorThrown );
},
});
});
});

yii2: call controller action in sortable jquery with ajax

I am using jquery sortable plugin to drag and drop items and setting their order. But I am unable to get the response from Ajax. I want to call the controller action from the js so that when I drag the item and drop it, then a response should come. The drag and drop functionality is working fine.
I tried this:
My View:
<div class="status-index info">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<ul class="sortable_status">
<?php
$items = StatusType::find()->orderBy('order')->all();
//var_dump($items);exit;
//$content = array();
foreach ($items as $item) {
echo '<li class="text-items"><label for="item'.$item->order.'"><span class="items-number">'.$item->order.'</span></label>
<label id="item'.$item->order.'" />'.$item->title.'</label>
<br/>
</li>';
}
?>
</ul>
</div>
JS:
$(function () {
var LI_POSITION = 'li_position';
$("ul.sortable_status").sortable({
update: function(event, ui) {
//create the array that hold the positions...
var order = [];
//loop trought each li...
$('.sortable_status li').each( function(e) {
//add each li position to the array...
// the +1 is for make it start from 1 instead of 0
order.push( $(this).attr('id') + '=' + ( $(this).index() + 1 ) );
});
// join the array as single variable...
var positions = order.join(';')
//use the variable as you need!
alert( positions );
// $.cookie( LI_POSITION , positions , { expires: 10 });
}
/*handle : '.handle',
update : function () {
var order = $('.sortable_status').sortable('serialize');
$(".info").load("process-sortable.php?"+order);
} */
});
});
Controller:
public function actionSortable()
{
/* foreach ($_GET['text-items'] as $position => $item)
{
$sql[] = "UPDATE `status_type` SET `order` = $position WHERE `id` = $item";
}*/
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
echo '
empty
';
}
}
why don't use an ajax call on stop ?
$("ul.sortable_status").sortable({
stop: function(event, ui) {
$.ajax({
type: "POST",
url: myUrl
data: {my-data: "any-value"}
})
.success(function(data) {
//your logic here
})
.fail(function() {
//your logic here
});
}
});
I used to define in my layout on the head tag of my html my variables as following
<head>
<script>
var myUrl = "<?php echo Url::to(['controller/action']); ?>";
</script>
</head>

Codeigniter Calendar template modification of content

I'm using the CI Calendar. The db that I've connected it with has columns for: date, hours, category, and notes. I started out with the same format as in this tutorial from net tuts+. I can get the calendar to display the notes on the appropriate day, but I'm not sure how to split up the content section into hours, category and notes. I know I have to modify the generate calendar in the system file, but not sure how to do it.
Here's my code:
Controller:
function index($year = null, $month = null)
{
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$this->load->model('calendar_model');
if ($day = $this->input->post('day')) {
$this->calendar_model->add_calendar_data(
"$year-$month-$day",
$this->input->post('hours'),
$this->input->post('category'),
$this->input->post('notes')
);
}
$data['calendar'] = $this->calendar_model->generate($year, $month);
// Load a view in the content partial
$this->template->content->view('includes/user_navigation');
$this->template->content->view('dashboard', $data);
// Display the template
$this->template->publish();
}
Model:
<?php
class Calendar_model extends CI_Model {
var $conf;
function Calendar_model()
{
parent::__construct();
}
function get_calendar_data($year, $month) {
$query = $this->db->select()->from('calendar')
->like('date', "$year-$month", 'after')->get();
$cal_data = array();
foreach ($query->result() as $row) {
$cal_data[substr($row->date,8,2)] = $row->notes;
/* Testing purposes */
echo "<p>" . $row->date . "</p>";
echo"<p>" . $row->hours . "</p>";
echo "<p>" . $row->category . "</p>";
echo "<p>" . $row->notes . "</p>";
}
return $cal_data;
}
function add_calendar_data($date, $hours, $category, $notes) {
if ($this->db->select('date')->from('calendar')
->where('date', $date)->count_all_results()) {
$this->db->where('date', $date)
->update('calendar', array(
'date' => $date,
'hours' => $hours,
'category' => $category,
'notes' => $notes
));
} else {
$this->db->insert('calendar', array(
'date' => $date,
'hours' => $hours,
'category' => $category,
'notes' => $notes
));
}
}
function generate ($year, $month) {
$this->load->library('calendar');
$cal_data = $this->get_calendar_data($year, $month);
return $this->calendar->generate($year, $month, $cal_data);
}
}
Calendar template:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Calendar configuration
|--------------------------------------------------------------------------
| This file will contain the settings for the calendar template library.
|
*/
$config['day_type'] = 'long';
$config['show_next_prev'] = true;
$config['next_prev_url'] = base_url('index.php/calendar/display');
$config['template'] = '
{table_open}
<table class="calendar">
{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><<</th>{/heading_previous_cell}
{heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th>>></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
{week_day_cell}
<th class="day_header">{week_day}</th>
{/week_day_cell}
{cal_row_start}<tr class="days">{/cal_row_start}
{cal_cell_start}<td class="day">{/cal_cell_start}
{cal_cell_content}
<div class="day_num">{day}</div>
<div class="content">
<div class="category">{category}
<div class="hours">{hours}
<div class="notes">{notes}
{content}
</div>
</div>
</div>
</div>
{/cal_cell_content}
{cal_cell_content_today}
<div class="today"><div class="day_num">{day}</div>
<div class="content">{content}</div></div>
{/cal_cell_content_today}
{cal_cell_no_content}
<div class="day_num">{day}</div>
{/cal_cell_no_content}
{cal_cell_no_content_today}
<div class="today"><div class="day_num">{day}</div></div>
{/cal_cell_no_content_today}
';
js code in my view:
$(document).ready(function(){
var date;
// === Prepare calendar === //
$('.calendar .day').click(function() {
day_num = $(this).find('.day_num').html();
$("#activityModal").modal('toggle');
$('#add-event-submit').click(function(){
var hrs = document.getElementById('activityHrs').value;
var note = document.getElementById('activityNotes').value;
var cat = document.getElementById('activityCats');
var selectedCat = cat.options[cat.selectedIndex].text;
var message = "Date: " + date + "\n";
message += "hrs: " + hrs + "\n";
message += "category: " + selectedCat + "\n";
message += "note: " + note;
message += "day num: " + day_num;
//alert(message);
if (hrs != null && selectedCat !=null && note !=null) {
$.ajax({
url: window.location,
type: 'POST',
data: {
day: day_num,
hours: hrs,
category: selectedCat,
notes: note
},
success: function(msg) {
location.reload();
}
});
}
});
});
});

Resources