tags:

views:

69

answers:

3

I want to add the attribute href to the end of an url:

This should be pretty easy. This is what I have, but I think something's wrong.

$('.delete-code').click(function() {
    var row = $(this).parent().parent();
    $.ajax({
        type: "POST",
        url: "http://website.com/admin/home/deleteCode/"+$(this).attr('href'),
        data: $(this).attr('href'),
        success: function() {
            $(row).hide();
        }
    });
    return false;
});

This works when I hard-code in the href

A: 

I'm confused. Is $(this) the '.delete-code'? The first line doesn't appear to be in the code block.

Giles Van Gruisen
Hi Giles, better make answers like this a comment next time, as it's not really an answer. Cheers, Tom.
Tom Bartel
I actually tried to do so in a comment, but it wouldn't let me write a comment for some odd reason. I still cannot see an "add comment" button under the question or any of the answers but this one.
Giles Van Gruisen
+1  A: 

Your code should work. The problem is the url. Some browsers need to get 200 OK to call the success callback.

Try changing:

url: "http://website.com/admin/home/deleteCode/"+$(this).attr('href'), 

to:

url: "http://www.flickr.com/search/?q="+$(this).attr('href'),

It should work.

Also you may want to change some little things:

  1. The data property is redundant and don't work with pretty urls out of the box.
  2. jQuery has a $.get method to make GET requests.
  3. closest('tr') rather than parent().parent() will make your code more readable.
  4. href is an element attribute, so it can be accessed directly trough DOM

So maybe this can be a better option depending on what you need:

$('.delete-code').click(function() {
    var tr= $(this).closest('tr')
    $.get("http://www.flickr.com/search/?q=" + this.href, 
       function(){
          tr.hide()
       })
    return false
})

Good luck.

Julio Protzek
This wasn't a fix, but this is the best answer, so I'm awarding you!
Kevin Brown
A: 

there's nothing wrong with your code, it's probably just your DOM traversal or the way you're doing your AJAX.

and Julio Protzek is right, unless you're using an error function or want to make a synchronous XMLHttpRequest (a fairly rare case), you could just as easily say

$('.delete-code').click(function() {
    var row = $(this).parent().parent();
    $.get(
        "http://website.com/admin/home/deleteCode/"+$(this).attr('href'),
        {}, // or { data: $(this).attr('href') }, if you needed to send that
        success: function() {
            $(row).hide();
        }
    });
    return false;
});

and remember, unless .delete-code applies to an <a class="delete-code"> element, it's a different element you're trying to get the .attr('href') from.

Dan Beam