I'm implementing a like button in yii,when i click on the button it calls a controller action which increases the number of likes by 1, i show the changed value in the Button label,how do i do it?
here is my view,what do i change ?
<?php $id =$data->id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'success'=>'js:function(data){
')
);
?>
You should try the following
<?php $id =$data->id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'replace'=>'#buttonId')
),
array(
'id'=>'buttonId'
);
?>
However, I suggest using sending parameters as data for AJAX like this:
<?php $id =$data->id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like),
array(
'type'=>'POST',
'data'=>array("id"=>$id),
'replace'=>'#buttonId')
),
array(
'id'=>'buttonId'
);
?>
http://www.yiiframework.com/doc/api/1.1/CHtml#ajax-detail
replace: string, specifies the selector whose target should be replaced by the AJAX
Related
I am trying to build a simple interface in Woocommerce where a product gets added straight to the mini cart next to it with AJAX, rather than having the page refresh every time you add an item to the cart. Unfortunately I cannot get the AJAX to work and the page just keeps refreshing.
woocommerce.php - the default woocommerce page:
<?php
//LOOP THROUGH ALL PRODUCTS
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
echo "<ul class='mylisting'>";
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$id = $product->get_id();
$item_name = $product->get_name();
if( $product->is_type( 'variable' ) ){
$class = "variable-product";
} else {
$class = NULL;
}
//OUTPUT PRODUCTS
?>
<li>
<a class="menu-link <?php echo $class; ?>" data-product_id="<?php echo $id; ?>" href="/wpdev/shop/?add-to-cart=<?php echo $id; ?>"><?php echo $item_name." - ".$id; ?></a>
</li>
<?php if( $product->is_type( 'variable' ) ) : ?>
<div id="product-popup-<?php echo $id; ?>" class="product-popup">
<div class="popup-inner">
<?php woocommerce_variable_add_to_cart(); ?>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
echo "</ul>";
wp_reset_query();
?>
<!-- DISPLAY MINI CART -->
<div id="mini-cart-container">
<?php woocommerce_mini_cart(); ?>
</div>
main.js - Main javascript file:
$('.menu-link').click(function(){
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
functions.php
function ajax_update_mini_cart() {
echo wc_get_template( 'cart/mini-cart.php' );
die();
}
add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );
The goal is to get the woocommerce_mini_cart() function to update with ajax. Is this possible?
I suspect the problem lies with the way I have coded the javascript ajax function, but I'm not sure. Any help would be greatly appreciated.
UPDATE: Moe's solution below has now been added, which has stopped the page reloading but the cart still doesn't update. Echoing some text inside the ajax_update_mini_cart() function does ajax that text inside the mini-cart-container div where the mini-cart should be, which proves (I think) that the javascript function and the php function is working. I think for some reason the problem comes when the echo wc_get_template( 'cart/mini-cart.php' ); is placed inside the function. Does anyone know why this is?
its following the href. try the following
$('.menu-link').click(function(e){
e.preventDefault();
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
I have an ajax form that filters posts based on the category.
Setup:
HTML form
PHP function to echo ouput
jQuery ajax request to load php
function
Question: How can I parse a value to the php function ($test, see below) from within the jQuery ajax function?
Form - Outputs html select field and button to filter posts
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
echo '<select name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
<div id="response"></div>
PHP function - Outputs result on button click in HTML form
function misha_filter_function($test){
// Do something with $test, but how to parse it with jQuery into this php function?
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
jQuery - Question: how to parse php value $test to the above php function?
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
You serialize data so accesed by:
parse_str($_POST['data'], $inputValues); //$inputValues will be array with your form fields
I an trying to create a image widget with wp editor. I see the editor but i cant the text like make it bold or bigger nither i see the tab switch from visual to text. Following is my code:
Thanks in advance.
<input type="hidden" id="<?php echo esc_attr($this->get_field_id('description')); ?>" name="<?php echo esc_attr($this->get_field_name('description')); ?>" value="<?php echo esc_attr($instance['description']); ?>" />
<?php
$edi_name = esc_attr($this->get_field_name('description'));
$content = $instance['description'];
$editor_id_new = esc_attr($this->get_field_id('description'));
$settings = array( 'media_buttons' => false,
'textarea_rows' => 6,
'textarea_name' => $edi_name,
'teeny' => false,
'menubar' => false,
'default_editor' => 'tinymce',
'quicktags' => false
);
wp_editor( $content, $editor_id_new, $settings );
?>
<script>
(function($){
tinyMCE.execCommand('mceAddEditor', false, '<?php echo $this->get_field_id('description'); ?>');
})(jQuery);
</script>
Short answer: Because there is a hidden widget where the TinyMCE appears first.
Long answer (sorry, a very long answer):
Go to the Codex and copy the example widget Foo_Widget to make sure we are talking about the same code. Now open your IDE (not an editor) and write a short testing widget as plugin. Starting with a minimal plugin header...
<?php
/*
Plugin Name: Widget Test Plugin
Description: Testing plugincode
*/
... adding the widget code from the codex and registering the widget with the add_action() call. Now modify the form method within the widget class as shown here:
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'text_domain' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
/*** add this code ***/
$content = 'Hello World!';
$editor_id = 'widget_editor';
$settings = array(
'media_buttons' => false,
'textarea_rows' => 3,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings );
/*** end editing ***/
}
Go to your blog, activate the plugin, go to the widget page and drag the Foo Widget into a sidebar. You will see it will fail.
Do you see the Foo Widget description on the left side? Do a right click on the description and choose 'Inspect' from your developer tools (you have some developer tools like FireBug or Chrome DevTools, huh? In FireFox you can also choose the build in 'Inspect Element'). Browse through the HTML code and you will see there is an editor wrap inside the 'hidden' widget.
You can see one editor in the sidebar on the right and there is an editor in the 'hidden' widget on the left. This cannot work properly because TinyMCE don't know which editor should be used.
What do we need?
We need a unique ID for our editor.
/*** add this code ***/
$rand = rand( 0, 999 );
$ed_id = $this->get_field_id( 'wp_editor_' . $rand );
$ed_name = $this->get_field_name( 'wp_editor_' . $rand );
$content = 'Hello World!';
$editor_id = $ed_id;
$settings = array(
'media_buttons' => false,
'textarea_rows' => 3,
'textarea_name' => $ed_name,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings );
/*** end edit ***/
Modify the code within the form method again with the code above. We create a unique number with rand() and append this number to the id and name attributes. But stop, what about saving the values???
Go to the update method and add die(var_dump($new_instance)); in the first line. If you press Save on the widget, the script will die and print out the submitted values. You will see there is a value like wp_editor_528. If you reload the page and save the widget again, the number will be changed to something else because it is a random number.
How will I know which random number was set in the widget? Simply send the random number with the widget data. Add this to the form method
printf(
'<input type="hidden" id="%s" name="%s" value="%d" />',
$this->get_field_id( 'the_random_number' ),
$this->get_field_name( 'the_random_number' ),
$rand
);
In the update routine, we can now access the random number with $new_instance['the_random_number']; and so we can access the editor content with
$rand = (int) $new_instance['the_random_number'];
$editor_content = $new_instance[ 'wp_editor_' . $rand ];
die(var_dump($editor_content));
As you can see, the editor content will be submitted and you can save it or do anything else with it.
Caveat
The editor content is only submitted correctly if the TinyMCE is not in visual mode (WYSIWYG mode). You have to switch to the text mode befor press 'Save'. Otherwise the predefined content (in this case $content = 'Hello World!';) is submitted. I don't now why, but there is a simple workaround for this.
Write a small jQuery script that triggers the click on the 'text' tab before saving the widget content.
JavaScript (saved as widget_script.js somewhere in your theme/plugin folders):
jQuery(document).ready(
function($) {
$( '.widget-control-save' ).click(
function() {
// grab the ID of the save button
var saveID = $( this ).attr( 'id' );
// grab the 'global' ID
var ID = saveID.replace( /-savewidget/, '' );
// create the ID for the random-number-input with global ID and input-ID
var numberID = ID + '-the_random_number';
// grab the value from input field
var randNum = $( '#'+numberID ).val();
// create the ID for the text tab
var textTab = ID + '-wp_editor_' + randNum + '-html';
// trigger a click
$( '#'+textTab ).trigger( 'click' );
}
);
}
);
And enqueue it
function widget_script(){
global $pagenow;
if ( 'widgets.php' === $pagenow )
wp_enqueue_script( 'widget-script', plugins_url( 'widget_script.js', __FILE__ ), array( 'jquery' ), false, true );
}
add_action( 'admin_init', 'widget_script' );
That's it. Easy, isn't it? ;)
Actual Credit Goes To The Author Of Writting This Test Plugin #Ralf912
Reference URL : Why Can't wp_editor Be Used in a Custom Widget?
I made some improvements to this code in case somebody needs it:
on the form function of the widget I updated the code:
$rand = !empty( $instance['the_random_number']) ? $instance['the_random_number'] : rand( 0, 999 );
$ed_id = $this->get_field_id( 'wp_editor_' . $rand );
$ed_name = $this->get_field_name( 'wp_editor_' . $rand );
$content = !empty( $instance['the_random_number']) ? $instance['wp_editor_' . $rand] : 'Content goes here!';
$editor_id = $ed_id;
$settings = array(
'media_buttons' => true,
'textarea_rows' => 3,
'textarea_name' => $ed_name,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings ); `
And I also reinitialized the editor because it was broken after save
jQuery(document).on('widget-updated', function(e, widget){
if(widget[0].id.includes("cw_pa_text_widget")) { // if it is the right widget
let editor ="widget-" + widget[0].id.substring(widget[0].id.indexOf('_') + 1);
let randNum = editor + "-the_random_number";
let wpEditorId = editor + "-wp_editor_" + document.getElementById(randNum).value;
var settings = {
quicktags: true,
};
wp.editor.initialize(wpEditorId, settings);
//create the ID for the text tab
var textTab = wpEditorId + '-tmce';
// trigger a click
document.getElementById(textTab).click();
}});
Thank you.
I have a form adding data into db. I have single input field and button which add more input fields on click. My question is how to grab in controller all inputs and send it to model. My code so far is:
jQuery:
<script>
$('a').click(function(e){
$('#inp').append('<div><input class = "new_input" type=text name="name[]"/><a class="remove_field "href="#"> X</a><div><br/>');
$('.remove_field').click( function(e){
e.preventDefault();
$(this).parent('div').remove();
})
});
</script>
form:
<?php
// Forma za unos podataka
echo $this->session->flashdata('item');
echo '<h4>Unesite podatke</h4>';
echo '<div id="warning"></div>';
$att = array('name'=>'form','onsubmit'=>" return validation()");
echo form_open('admin/crud/adding/',$att);
echo form_label('Novi podatak:', 'input_data_info') . br() . br();
$data = array(
'name' => 'input_data_info',
'id' => 'input_data_info',
'placeholder' => 'Unestite podatke',
);
echo form_input($data) . br() . br();
echo '<div id="inp"></div>';
echo "<a href='#'>".'Novi unos'."</a>" .br() .br();
echo form_submit('save', 'Snimi') . br() . br();
echo form_submit('add', 'Dodaj').br();
echo form_close();
?>
controller:
$input_data_info = (string)$this->input->post('input_data_info', TRUE);
//model za dodavanje podataka
$this->load->model('Data');
$query = $this->Data->add($input_data_info);
The first input field name is 'input_data_info' and then JQuery adds input fields with 'name[ ]'
As you want to pull the data from all the input fields, they , first need to have a common name.
So, rename the input field that you have created initially in the form to name= 'name[]' that makes your code:
$data = array(
'name' => 'name[]',
'id' => 'input_data_info',
'placeholder' => 'Unestite podatke',
);
Then in you controller use something like this:
$all_input_data = $this->input->post('name');
//the $all_input_data is an array containing all your input values.
i need to get the value of a variable in a javascript function to put it in a textfiled.
Javascripts function:
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
alert(arrendatario_id);
}
The alert give me the id of the selected row but i need to put the id in the textfield to save/create the form
Gridview
<div class="row">
<?php echo $form->labelEx($model,'zf_arrendatarios_arrendatario_id'); ?>
<?php
$arrendatarios = new ZfArrendatarios;
$this->widget('bootstrap.widgets.TbGridView',
array(
'id'=>'arrendatario',
'selectableRows'=>1,
'selectionChanged'=>'obtenerArrendatario',
'type'=>'striped bordered condensed',
'dataProvider'=>$arrendatarios->search(),
'filter' => $arrendatarios,
'template'=>"{items}\n{pager}",
'columns'=>array(
array('name'=>'arrendatario_id_personal', 'header'=>'DNI',),
array('name'=>'arrendatario_nombre', 'header'=>'Nombre'),
array('name'=>'arrendatario_email', 'header'=>'Email'),
),
));
?>
<?php
echo $form->textfield($model,'zf_arrendatarios_arrendatario_id',array('class'=>'input input_r input_pryk', 'value'=>$arrendatario));
?>
<?php echo $form->error($model,'zf_arrendatarios_arrendatario_id'); ?>
</div>
So i need that id that the function capture to fill my textfield.
I tried
$arrendatario= "<script> document.write(arrrendatario_id) </script>";
But it print me the string not the value.
For your requirement, you can set the textfield value in below js function
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
$(".input_pryk").val(arrendatario_id );// input_pryk should be class for this text field alone.
}
Then you will get in controller while submitting the form.