Skip to content

Instantly share code, notes, and snippets.

@themeblvd
Created November 13, 2012 19:52
Show Gist options
  • Save themeblvd/4067968 to your computer and use it in GitHub Desktop.
Save themeblvd/4067968 to your computer and use it in GitHub Desktop.
// The PHP
/**
* Add primary item to cart (Ajax).
*/
function themeblvd_ajax_add_to_cart() {
if( isset($_POST['download_id']) && check_ajax_referer( 'edd_ajax_nonce', 'nonce' ) ) {
global $post;
if( ! edd_item_in_cart($_POST['download_id'] ) ) {
$options = is_numeric( $_POST['price_id']) ? array('price_id' => $_POST['price_id']) : array();
$key = edd_add_to_cart( $_POST['download_id'], $options );
echo themeblvd_checkout_button();
echo '[(=>)]';
echo edd_get_cart_quantity();
echo '[(=>)]';
echo themeblvd_floating_cart( $_POST['current'] );
} else {
echo 'incart';
}
}
die();
}
add_action( 'wp_ajax_nopriv_themeblvd_add_to_cart', 'themeblvd_ajax_add_to_cart' );
add_action( 'wp_ajax_themeblvd_add_to_cart', 'themeblvd_ajax_add_to_cart' );
// The JS
// edd_scripts.ajaxurl = http://wpjumpstart.com/wp-admin/admin-ajax.php, which is the virtual mapped domain.
jQuery(document).ready(function($){
// Add Jump Start to cart
$('.buy-jumpstart').click(function(){
var el = $(this),
added = el.closest('.nav-middle').find('.added'),
item_download = el.attr('data-id'),
current_page = el.attr('data-current'),
item_price_id = false;
$.ajax({
type: "POST",
url: edd_scripts.ajaxurl,
data:
{
action: 'themeblvd_add_to_cart',
download_id: item_download,
price_id : item_price_id,
current : current_page,
nonce: edd_scripts.ajax_nonce
},
beforeSend: function()
{
el.addClass('loading').find('.loader').fadeIn();
el.closest('li').css('position', 'relative').prepend('<div class="click-protect"></div>');
},
success: function(response)
{
// Wait 1.5 seconds
setTimeout(function () {
var elements = response.split('[(=>)]');
if( elements.length == 3 )
{
// Update "My Cart" Quantity
$('#my-cart .cart-num').html(elements[1]);
// Update floating shopping cart
$('#floating-cart .ajax-mitt').html(elements[2]);
// Replace Buy button with Checkout button
el.closest('li').html(elements[0]);
// Fade in and slide down success message
added.css({
'display': 'block',
'opacity': 0
}).animate({
top: '+=20',
opacity: 1
}, 300, function() {
setTimeout(function () {
added.fadeOut();
}, 2000);
});
}
else
{
// Something went wrong, refresh the page.
var url = window.location.href.split('?'), url = url[0];
window.location.replace(url);
}
}, 1500);
}
});
return false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment