I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.
functions:
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
Input:
<?php if (empty (WC()->cart->get_coupons())): ?>
<span id="coupon-form">
<?php if ( wc_coupons_enabled() ) { ?>
<form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
<?php } else { ?>
<form id="apply-promo-code" class="widget_shopping_cart__coupon">
<?php } ?>
<label id="promo-code" for="coupon-code">Promo Code:</label>
<input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
<button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
<?php do_action( 'woocommerce_cart_coupon' ); ?>
<?php do_action( 'woocommerce_cart_actions' ); ?>
</form>
<?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
<span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>
<?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
<?php wc_cart_totals_coupon_html( $coupon ); ?>
</span>
<?php endforeach; ?>
jQuery:
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
ob_start();
woocommerce_mini_cart();
$cart_html = ob_get_clean();
return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
The output buffer is used here as woocommerce_mini_cart uses wc_get_template which just echoes out the content. The output buffer will allow you to capture this as a string.
Now you need to tell jQuery that you're expecting HTML back from the server...
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...
success: function (response) {
console.log(response);
jQuery('.mini-cart-wrapper').html(response);
},
I am making a WordPress website, which is made up of a Woocommerce Store + Blog section. Both in the Store and on the Blog there is a search engine that shows instant results with AJAX. What I want to do is that, depending on the page where the user is (Blog page or Store page), the search engine will only show results of articles or products, respectively.
After googling and testing, I understood that the conditional tags of Wordpress (is_home (), is_shop (), etc) don't work if they are called from the functions.php file, and the AJAX php function I'm using is effectively inside the functions.php.
The AJAX php function is as follows:
<?php
/**
* Adding ajax search functionality to the theme
*/
add_action('wp_ajax_nopriv_ajax_search','ajax_search');
add_action('wp_ajax_ajax_search','ajax_search');
function ajax_search(){
global $post;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
's' =>$_POST['term'],
'posts_per_page' =>10
);
$query = new WP_Query( $args );
// display results
if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post(); ?>
<li>
<?php
$terms = get_the_terms( $post->ID, 'category' );
foreach ($terms as $term) {
break;
} ?>
<a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a>
<div class="clear"></div>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
<?php else: ?>
<li class="no-results-ajax">No results.</li>
<?php endif; ?>
<?php exit;
}
?>
The JQuery function linked with the previous function is as follows:
function buscar_ajax(input1, input2) {
input1.keyup(function(e) {
// prevent browser autocomplete
jQuery(this).attr('autocomplete','off');
// get search term
var searchTerm = jQuery(this).val();
var urlFull = window.location.href; // URL completa
var ruta = window.location.pathname; // URL sin "http://dominio.com"
var dominio = urlFull.replace(ruta,''); // URL solo "http://dominio.com"
if(searchTerm.length > 2) {
jQuery.ajax({
url: dominio + "/wp-admin/admin-ajax.php",
type:"POST",
data:{
'action':'ajax_search',
'term' :searchTerm
},
success:function(result){
input2.fadeIn(200).html(result);
}
});
} else {
input2.fadeOut(200);
}
if(searchTerm.length == 0){
input2.hide();
}
if(e.keyCode == 27){
jQuery(this).val('');
input2.hide();
}
jQuery('body').click(function(e){
if ( !jQuery(e.target).hasClass("busqueda") ) {
input2.fadeOut(200);
jQuery(this).val('');
}
});
});
input1.keypress(function(e) {
if(e.keyCode == 27){
jQuery(this).val('');
input2.fadeOut(200);
}
});
}
var buscaHead1 = jQuery('input#s');
var buscaHead2 = jQuery('ul#dhemy-ajax-search');
buscar_ajax( buscaHead1, buscaHead2 );
And the HTML code of the search form:
<form role="search" method="get" id="buscador-blog" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input class="busqueda" type="text" value="" name="s" id="s" placeholder="Busca en el blog..."/>
<ul id="dhemy-ajax-search"></ul> <!-- AJAX search -->
<input type="submit" id="searchsubmit" value="" />
<input type="hidden" name="search-type" value="post" />
</form>
So far, the result is that AJAX shows blog articles or products or articles and products. (changing 'post' to 'product' in the 'post_type' parameter of the $ args array). I need that, if the person is on the Store page, they only show products and if they are on the Blog page, they only show posts.
This could be done if only I had some conditional to evaluate what type of page the user is viewing, and that is where I am trapped.
I very much appreciate any help or guidance you can give me.
how to show $data value in form input field?
<head>
<script>
$(function () {
$("#task_id").change(function () {
var task_id = $(this).val();
var url = "status/tasks/get_task_info/" + task_id;
$.ajax({
url: url,
beforeSend: function () {
$(".load-taskinfo").html('<img src="images/ajax/ajax-loader10.gif">');
},
success: function (response) {
$data = JSON.parse(response);
}
});
});
});
</script>
</head>
<body>
<div class="span3">
<div class="control-group <?php echo (form_error('progress_percent')) ? 'error' : ''; ?>">
<label class="control-label" for="progress_percent">Progress (In %) :</label>
<div class="controls">
<?php echo form_input(array(
'name' => 'progress_percent',
'id' => 'progress_percent',
'maxlength' => 160
)); ?>
<?php if (form_error('progress_percent')) : ?>
<span class="help-inline">
<?php echo form_error('progress_percent'); ?>
</span>
<?php endif; ?>
</div>
</div>
</div>
</body>
In your success callback, use jQuery selector to select the input by ID or by name, and fill its value.
success: function (response) {
var $data = JSON.parse(response);
$('#progress_percent').val($data);
}
I chose gallerycms to build my own gallery but when I try to make it as module into my codeigniter cms I get this error HTTP Error. I don't know why I see this error although I was copying all controllers, models, views, core files and I still get this error.
NOTICE: uploadify work good with Gallerycms but when I want to add it into my cms as a module I get this error:
firebug code
<script type="text/javascript">
$(document).ready(function() {
$('.btn-group > a').tooltip();
$('#upload-btn').hide();
$('#new-images').hide();
$('a.img-fancy').fancybox();
$('.image-delete-btn').click(function() {
deleteUrl = $(this).attr('action');
});
$('#image-modal').on('show', function() {
$('#image-modal-delete-btn').attr('href', deleteUrl);
});
$("#sortable").sortable({
handle : '.drag-handle',
update : function () {
var order = $('#sortable').sortable('serialize', { key : 'order_num[]' });
$.ajax({
url : 'http://localhost/gallery/album/reorder?' + order,
type : 'GET',
cache : false,
success : function(response) {
$('#reorder-feedback').show();
$('#reorder-feedback').html('<a class="close" data-dismiss="alert">x</a><strong>Changed image order successfully.</strong>');
},
error : function(jqXHR, textStatus, errorThrown) {
alert('An error occured when ordering the images.');
}
});
}
});
$( "#sortable" ).disableSelection();
$('#file_upload').uploadify({
'uploader' : 'http://localhost/gallery/webroot/flash/uploadify.swf',
'script' : 'http://localhost/gallery/api/upload/3',
'cancelImg' : 'http://localhost/gallery/webroot/images/cancel.png',
'folder' : '/webroot/uploads',
'auto' : false,
'multi' : true,
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'fileDesc' : 'Image files',
'sizeLimit' : 2097152, // 2MB
'wmode' : 'opaque',
'onSelect' : function(event, ID, fileObj) {
$('#upload-btn').show();
},
'onCancel' : function(event, ID, fileObj) {
$('#upload-btn').hide();
},
'onError' : function(event, ID, fileObj, errorObj) {
},
'onComplete' : function(event, ID, fileObj, response, data) {
var fileName = response;
$('#upload-btn').hide();
$('#new-images').show();
$.ajax({
url : 'http://localhost/gallery/album/resize/3/' + response,
type : 'POST',
cache : false,
success : function(response) {
if (response !== 'failure') {
var new_image = '<li><img src="http://localhost/gallery/webroot/uploads/' + response + '" /><br />' + response + '</li>';
$('#new-image-list').append(new_image);
} else {
var fail_message = '<li>Thumbnail creation failed for: ' + fileObj.name + '</li>';
$('#new-image-list').append(fail_message);
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert('Error occurred when generating thumbnails.');
}
});
}
});
});
</script>
api controller
/**
* Handles image uploads.
*
* #param type $album_id
*/
public function upload($album_id)
{
$config = array();
$config['upload_path'] = './webroot/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048'; // 2MB
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('Filedata'))
{
header('HTTP/1.1 500 Internal Server Error');
exit();
}
else
{
$upload_info = $this->upload->data();
$album_config = $this->config_model->get_by_album_id($album_id);
// Insert file information into database
$now = date('Y-m-d H:i:s');
$order_num = $this->image_model->get_last_order_num($album_id);
if (empty($order_num))
{
$order_num = 0;
}
$order_num++;
$image_data = array(
'album_id' => $album_id,
'uuid' => $this->create_uuid(),
'name' => $upload_info['file_name'],
'order_num' => $order_num,
'caption' => '',
'raw_name' => $upload_info['raw_name'],
'file_type' => $upload_info['file_type'],
'file_name' => $upload_info['file_name'],
'file_ext' => $upload_info['file_ext'],
'file_size' => $upload_info['file_size'],
'path' => $config['upload_path'],
'full_path' => $upload_info['full_path'],
'published' => $album_config->auto_publish,
'created_at' => $now,
'updated_at' => $now,
);
$image_id = $this->image_model->create($image_data);
$this->album_model->update(array('updated_at' => $now), $album_id);
echo $image_id;
}
}
}
views/images.php
<?php
$includes = array(
'js' => array('jquery-ui-1.8.18.custom.min.js', 'swfobject.js', 'jquery.uploadify.v2.1.4.min.js', 'fancybox/jquery.fancybox-1.3.4.pack.js'),
'css' => array('uploadify.css', 'fancybox/jquery.fancybox-1.3.4.css'));
?>
<?php $this->load->view('album/inc/header', $includes); ?>
<?php if (isset($flash)): ?>
<div class="alert alert-success"><a class="close" data-dismiss="alert">x</a><strong><?php echo $flash; ?></strong></div>
<?php endif; ?>
<div class="w100" style="margin-bottom: 10px;">
<ul class="pager">
<li class="previous">
← Back to albums
</li>
</ul>
<div class="well">
<h4 style="margin-bottom: 10px;">Upload images for album: <?php echo $album->name; ?></h4>
<input id="file_upload" type="file" name="file_upload" />
<p id="upload-btn" style="margin:10px 0;">
Upload Files
</p>
<div id="new-images">
<h4>Uploaded Images</h4>
<p><a class="btn" href="<?php echo site_url("album/images/$album->id"); ?>" style="margin: 10px 0;"><i class="icon-refresh"></i> Refresh</a></p>
<ul id="new-image-list"></ul>
<div class="clear"></div>
</div>
</div>
</div>
<div id="reorder-feedback" class="alert alert-success" style="display: none;"></div>
<span class="left w75">
<?php
$total_file_size = 0;
$total_images = 0;
$img_url = '';
?>
<?php if (isset($images)): ?>
<ul id="sortable">
<?php foreach ($images as $image): ?>
<?php
$total_file_size += $image->file_size;
$total_images++;
$img_url = base_url() . 'webroot/uploads/' . $image->file_name;
?>
<li id="image_<?php echo $image->id; ?>" class="ui-state-default" style="height: <?php echo $config->thumb_height + 10; ?>px">
<div class="drag-handle" style="height: <?php echo $config->thumb_height + 5; ?>px"></div>
<div class="image-container">
<a class="album-images img-fancy thumbnail" href="<?php echo $img_url; ?>" title="<?php echo $image->caption; ?>">
<img src="<?php echo base_url() . 'webroot/uploads/' . $image->raw_name . '_thumb' . $image->file_ext . '?r=' . rand(); ?>" alt="<?php echo $image->caption; ?>" />
</a>
</div>
<div class="info" style="left: <?php echo $config->thumb_width + 50; ?>px">
File name: <?php echo $image->name; ?><br />
Caption:
<?php if (empty($image->caption)): ?>
Create one
<?php else: ?>
<?php echo $image->caption; ?>
<?php endif; ?>
<br />
<?php /* Comments: <?php echo $image->comments; ?><br /> */ ?>
File size: <?php echo $image->file_size; ?> KB<br />
</div>
<div class="btn-group">
<i class="icon-zoom-in"></i>
<i class="icon-download-alt"></i>
<i class="icon-pencil"></i>
<?php /* <i class="icon-comment"></i> */ ?>
<?php if ($image->published == 1): ?>
<i class="icon-ok icon-white"></i>
<?php else: ?>
<i class="icon-ok"></i>
<?php endif; ?>
<i class="icon-remove icon-white"></i>
</div>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</span>
<span class="right w20">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header"><?php echo $album->name; ?></li>
<li><i class="icon-pencil"></i>Rename</li>
<li><i class="icon-cog"></i>Configure</li>
<li class="nav-header">Info</li>
<li>Images: <?php echo $total_images; ?></li>
<li>Album file size: <?php echo round($total_file_size / 1024, 2); ?> MB</li>
</ul>
</div>
</span>
<div class="clear"></div>
<div class="modal hide fade" id="image-modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Delete Image</h3>
</div>
<div class="modal-body">
<p><strong>Are you sure you want to delete this image?</strong></p>
</div>
<div class="modal-footer">
<a id="image-modal-delete-btn" href="#" class="btn btn-danger">Delete</a>
Cancel
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.btn-group > a').tooltip();
$('#upload-btn').hide();
$('#new-images').hide();
$('a.img-fancy').fancybox();
$('.image-delete-btn').click(function() {
deleteUrl = $(this).attr('action');
});
$('#image-modal').on('show', function() {
$('#image-modal-delete-btn').attr('href', deleteUrl);
});
$("#sortable").sortable({
handle : '.drag-handle',
update : function () {
var order = $('#sortable').sortable('serialize', { key : 'order_num[]' });
$.ajax({
url : '<?php echo base_url(); ?>album/reorder?' + order,
type : 'GET',
cache : false,
success : function(response) {
$('#reorder-feedback').show();
$('#reorder-feedback').html('<a class="close" data-dismiss="alert">x</a><strong>Changed image order successfully.</strong>');
},
error : function(jqXHR, textStatus, errorThrown) {
alert('An error occured when ordering the images.');
}
});
}
});
$( "#sortable" ).disableSelection();
$('#file_upload').uploadify({
'uploader' : '<?php echo base_url(); ?>webroot/flash/uploadify.swf',
'script' : '<?php echo base_url(); ?>album/api/upload/<?php echo $album->id; ?>',
'cancelImg' : '<?php echo base_url(); ?>webroot/images/cancel.png',
'folder' : '/webroot/uploads',
'auto' : false,
'multi' : true,
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'fileDesc' : 'Image files',
'sizeLimit' : 2097152, // 2MB
'wmode' : 'opaque',
'onSelect' : function(event, ID, fileObj) {
$('#upload-btn').show();
},
'onCancel' : function(event, ID, fileObj) {
$('#upload-btn').hide();
},
'onError' : function(event, ID, fileObj, errorObj) {
},
'onComplete' : function(event, ID, fileObj, response, data) {
var fileName = response;
$('#upload-btn').hide();
$('#new-images').show();
$.ajax({
url : '<?php echo base_url(); ?>album/resize/<?php echo $album->id; ?>/' + response,
type : 'POST',
cache : false,
success : function(response) {
if (response !== 'failure') {
var new_image = '<li><img src="<?php echo base_url(); ?>webroot/uploads/' + response + '" /><br />' + response + '</li>';
$('#new-image-list').append(new_image);
} else {
var fail_message = '<li>Thumbnail creation failed for: ' + fileObj.name + '</li>';
$('#new-image-list').append(fail_message);
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert('Error occurred when generating thumbnails.');
}
});
}
});
});
</script>
I am not sure if this will help or not.
I ran into the same problem before,
then I realized when I uploaded the files to the server,
I was logged in as root user so the file owner is root.
The solution was to remove all uploaded files, then upload again using other user.
Now it's working well.
Hope that's work for you.
the problem with files extensions so i replaced this code
$config['allowed_types'] = 'gif|jpg|png';
with
$config['allowed_types'] = '*';
then i selected only extension i prefered from jquery code
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
You can modify mime in application/config/mimes.php
Change:
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'png' => array('image/png', 'image/x-png'),
To
'jpeg' => array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
'jpg' => array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
'jpe' => array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
'png' => array('image/png', 'image/x-png', 'application/octet-stream'),
It's should work :)
You did not provide us a detailed error. HTTP Error could mean many things.
1. Check your Firebug Console or Chrome Console for the Ajax POST and
see what it returns.
2. Make sure the folder the uploads save to is writable (CHMOD
Permissions).
One thing that catches my eye is:
$config['upload_path'] = './webroot/uploads/';
it looks like you have copy pasted this, make sure you give it a proper upload path.
i'm loading a post with ajax.
The code is
$(document).ready(function(){
loadPostsFun = function(){
$.ajax({
url: "http://lab1.koalamedia.es/ajax/",
//url: "/random/",
success: function(response){
$("#randomPost").html( response );
}
});
};
$("#another").click(function(){
loadPostsFun();
return false;
});
});
The response is generated by a custom template with this code:
<?php
query_posts('showposts=1&orderby=rand');
the_post();
$args = array( 'numberposts' => 1, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
?>
<?php
foreach( $rand_posts as $post ) : setup_postdata($post);
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php
//comments_template( '', true ); //this doesn't work
comment_form();
//wp_list_comments(''); //this doesn't work
?>
<?php endforeach; ?>
The ajax request works but the comments doesn't show.All the post data is there.
How can i show the comments?
neither comments_template or wp_list_comments work.
You can view a demo or download the template sample i've done here
Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.
Use get_comments(), pass the post ID as parameter:
$comments = get_comments(array ( 'post_id' => $post->ID );
if ( $comments )
{
foreach ( $comments as $comment )
{
print "<li>$comment->comment_author<br>$comment->comment_content</li>";
}
}
i've found the problem, i forgot to set the global variable:
global $withcomments;
i was using
$withcomments = true;
comments_template();
but without the global it didn't work.
Now works like normal comments do.