Brett
Brett

Reputation: 386

changing a href attr on the run with jquery ajax

I have a URL I am passing to jQuery AJAX.

<a href="/wishlist.php?sku=C5&amp;action=move&amp;qty=1" class="buttoncart black">Move To Wishlist</a>;

When it gets to the AJAX I want the change the href attribute to

<a href="/ajax_page.php?sku=C5&amp;action=move&amp;qty=1">Move blaf</a>

I'm still a newbie. I'm sure there must be a simple way. Here is my script.

var wishorder = {
    init: function(config){
        this.config = config;
        this.bindEvents();
    },
    bindEvents: function(){
        this.config.itemSelection.on('click',this.addWish);
    },
    addWish: function(e){
        console.log('working');
        console.log($(this).attr('href').pathname);
        var self = wishorder;

        $.ajax({
            //this is where im using the href and would like to change it
            //but i cant seem to access to get variables
            url: $(this).attr('href'),
            //url: '/ajax/ajax_move.php',
            type: 'GET',
            data: {
                sku: $(this).data('sku'),
                action: $(this).data('action'),
                qty: $(this).data('qty')
            },
            success: function(results){
                console.log(results);
                $('#cartcont').html(results);
            }
        });
        e.preventDefault();
    }
};
wishorder.init({
    itemSelection: $('#carttable tr a'),
    form: $('#cartfrm')
});

Upvotes: 1

Views: 2461

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use replace in your addWish logic to change the URL:

addWish: function(e){
    var self = wishorder;
    var url = $(this).attr('href').replace('wishlist.php', 'ajax_page.php');

    $.ajax({
        url: url ,
        type: 'GET',
        data: {
            sku: $(this).data('sku'),
            action: $(this).data('action'),
            qty: $(this).data('qty')
        },
        success: function(results){
            console.log(results);
            $('#cartcont').html(results);
        }
    });
    e.preventDefault();
}

Upvotes: 2

sudhansu63
sudhansu63

Reputation: 6180

You just need a string replacement.

var original_href = $('<a href="/wishlist.php?sku=C5&amp;action=move&amp;qty=1" class="buttoncart black">').attr('href');

var new_href = original_href.replace(/wishlist.php/, "ajax_page.php");

Upvotes: 1

Related Questions