jQuery: The Write Less, Do More JavaScript Library

Re: Pass custom data through to $.ajax success callback

by Michael Geary-3 :: Rate this Message:

Reply to Author | View in Thread


The general answer to a question like this is "use a closure." That is,
create a variable in an outer function which your inner function can read
later when it needs it.

But you're already doing this! The "user" variable in your click function is
unique to each instance of the anonymouse click() callback function. When
the ajax success callback is called later, it will have access to the very
same "user" variable that you created for this individual ajax call.

IOW, you're doing it exactly right. What made you think that "if the user
has kicked off several requests from different rows, the above defined user
var is long stale"? They don't share a "user" variable, each one has its
own.

Is your code not working?

-Mike

> Am I looking at the problem all wrong? How do you correlate
> your ajax initiating triggers with the DOM elements that
> require the update when the request returns through the
> success function?
>
> See the sample below which illustrates my goal:
>
> I know this is a commonplace challenge. Can you suggest a
> different approach? What have I missed? I feel so stupid right now...
>
> $(document).ready(function(){
>   $("table tbody tr td:last").click(function(){
>     var user = {
>       id:$(this).parent().attr("id");
>     };
>     $.ajax({
>       type: "POST",
>       url: "promote.jsp",
>       data:user,
>       dataType: "text",
>       success: function(dat){
>         // this is where I want a reference to the original
> user ID or the tr where the event originated
>         // so I could go back to that row and update the DOM.
>         // If the user has kicked off several requests from
> different rows, the above defined user var is long stale
>       }
>     });
>   });
> });
>
> <table width="100%">
>  <thead>
>   <tr>
>     <td>Name</td>
>     <td>Email</td>
>     <td>Role</td>
>   </tr>
>  </thead>
>  <tbody>
>   <tr id="2553">
>     <td>Jim</td>
>     <td>jim@...</td>
>     <td>Promote</td>
>   </tr>
>   <tr id="2553">
>     <td>Pam</td>
>     <td>pam@...</td>
>     <td>Promote</td>
>   </tr>
>   <tr id="2553">
>     <td>Ed</td>
>     <td>ed@...</td>
>     <td>Promote</td>
>   </tr>
>  <tbody>
> </table>
>
> On Jul 23, 12:29 pm, mmiller <mark.o.mil...@...> wrote:
> > I am looking for a way to pass a custom data object through to the
> > $.ajax success function.
> >
> > Specifically, I want to pass a <tr> DOM reference so that when a
> > specific request completes I know which table row from
> which to remove
> > my activity indicator.
> >
> > I've scoured the docs but can't see the way to do this with JQuery.
> >
> > Thank-you
>

 « Return to Thread: Pass custom data through to $.ajax success callback

LightInTheBox - Buy quality products at wholesale price!