Getting jQuery to return an ajax object

Posted by japancheese on Stack Overflow See other posts from Stack Overflow or by japancheese
Published on 2010-03-08T22:56:19Z Indexed on 2010/03/08 23:06 UTC
Read the original article Hit count: 389

Filed under:
|
|

Hello, The question title is a bit strange because I'm not exactly sure how to phrase the problem. The issue is that I have many links to which I want to bind a click event with an ajax call, and I'm just looking to refactor some duplicate code into a single area.

The links I'm trying to bind an ajax call only have one thing that differentiates them, and that's an id from a previously declared object. So I have lots of code that looks like this:

$("a.link").bind('click', function() {
           id = obj.id; 
           $.ajax({ 
                   url: "/set/" + id, 
                   dataType: 'json', 
                   type: "POST" 
           }) 
    });

I was trying to refactor it into something like this:

$("a.link").bind('click', ajax_link(obj.id));

 function ajax_link(id) {
      $.ajax({ 
             url: "/set/" + id, 
             dataType: 'json', 
             type: "POST" 
      }) 
 });

However, as you can imagine, this just actually makes the ajax call when the element is binded with the click event.

Is there an easy way to refactor this code so I can extract out the common ajax code into its own function, and hopefully reduce the number of lines of jQuery in my current script?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about refactor