M dunbavan
M dunbavan

Reputation: 1167

How can I post my href value in an ajax function?

I am trying to create an action that allows me to post an anchor href with an ajax call. Firstly the anchor tag is created with a backend set up so it cannot be inside a form etc so that is not going to work.

Here is the markup for the button, the href is added dynamically with js:

<a class="js-add-to-cart button buying-options buy-button" data-products-in-cart="<?= $products_in_cart ?>">
                Select a size
            </a>

I have currently got this code working which posts the anchor:

jQuery(function(){
                jQuery('a.buy-button').click(function(event) {
                    event.preventDefault();
                    jQuery.ajax({
                        url: jQuery(this).attr('href'),
                        type: 'POST',
                        async: true,
                        beforeSend: function(){
                            jQuery('#result').hide();
                            jQuery('#ajax-loader').show();
                        },
                        error: function(xhr, status, thrown){
                            alert(xhr + ',' + status+ ',' + thrown);
                        },
                        complete: function(){
                            jQuery('#ajax-loader').hide();
                        },
                        success: function(data) {
                            jQuery('#result').empty().append(data);
                            jQuery('#result').fadeIn('slow');
                        }
                    });
                });
        });

It works but my only issue is that it basically does a get request and in the header network response I get this:

Network response

This does not post the add to cart url and make the product added to cart.

Does anyone know how this can be done?

Cheers, Mark

Upvotes: 0

Views: 1066

Answers (2)

Flame
Flame

Reputation: 7570

try to see if the POST-action is actually triggered within the PHP code. It seems like it should be working.

Also the 'async' parameter is superfluous since you're already calling an A-jax function

Upvotes: 1

Rodik
Rodik

Reputation: 4092

perhaps using the .post() shorthand will help you (and also clean up your code).

I'm assuming that you are not using the $ alias for jQuery because you are not aware of it, and not because of any conflict issues.

$(function(){
  $('a.buy-button').click(function(event) {
    event.preventDefault();
    $('#result').hide();
    $('#ajax-loader').show();
    $.post($(this).attr('href'), function (data) {
      $('#ajax-loader').hide();
      $('#result').empty().append(data);
      $('#result').fadeIn('slow');
    });
  });
});

Upvotes: 0

Related Questions