1

Having some difficulty using a variable within an ajax() function. I know it is because the variable is not in the scope of the ajax() call but not sure how to fix this. I've read a bit about closures and callbacks for things like this but not really sure how to actually apply that to my code.

Code summary: on click() I get user_notes via ajax, and on that success I pop up a dialog box displaying the user_notes (all this works so far). Where it breaks down is when I then try and do another ajax call when the "Save" button is pressed. In that second ajax call user_notes is undefined within that scope.

How can I use user_notes within that second ajax call?

 $(".editSaved").click(function() {
            save_id = $(this).attr('id');
            var user_notes;

            //GET USER NOTES
            $.ajax ({
                url:"journal-util.php",
                data:"q=0&f=user_notes&save_id="+save_id,
                success: function(user_notes){

                    //BUILD SAVE DIALOG
                    div="<div><textarea rows=15 cols=27 id='RowSave'>"+user_notes+"</textarea></div>";
//AT THIS POINT USER_NOTES HAS A VALUE
                    success="<div>Updated!</div>";
                    $(div).dialog({ 
                        buttons: { 
                            "Save": function() { 
                                var that = this;
                                var un = user_notes; //tried this, didn't work
                                $.ajax ({
                                    url:"journal-util.php",
                                    data:"q=0&f=update&user_notes="+un, //un is empty
                                    success: function(result){
                                        alert(result);
                                        $(that).dialog("close");
                                        //$(success).dialog();
                                    }
                                })
                            },
                            "Cancel": function() { 
                                $(this).dialog("close");
                            } 
                        },
                        modal: true,
                        title: 'Delete',
                        resizable: false
                    });
                }
            });
        });
1
  • 1
    Is un empty at the point where you say var un = user_notes;? (Also, what is the var user_notes for, declared right near the top?) Commented Nov 23, 2011 at 5:37

3 Answers 3

2

Why doesn't work

The problem why your code is not working is that when your second AJAX success callback function is fired, the value user_notes holds might have already be altered or reset. To make it work, you need to capture the value of user_notes in that scope.

Solution

Replace your "Save" callback with a closure to hold the user_notes value within that scope.

"Save": function (un) {
          return function() {
                    var that = this;
                    $.ajax ({
                        url:"journal-util.php",
                        data:"q=0&f=update&user_notes="+un, 
                        success: function(result){
                            alert(result);
                            $(that).dialog("close");
                            //$(success).dialog();
                        }
                    });
                };
          } (user_notes),
Sign up to request clarification or add additional context in comments.

4 Comments

doesn't work. at the point you mention above user_notes already has a defined value. When I use it in the DIV a few lines down it has the right value.
@steven: The parameter in success: function(user_notes) is set automatically by jQuery (and will be the ajax response data).
A, mistake. user_notes is just the data of an Ajax callback. I will update the post soon.
@themerlinproject updated the post, see if it works. Sorry for the misunderstanding before.
1

Try this solution

un = $('#RowSave').val();

Hope this solves your problem

1 Comment

actually @amgates you've nailed what the problem actually was (I figured it out soon after asking). user_notes was working just fine within the new ajax call - I was just calling an old value. Your code above should be var un = $('#RowSave').val()
0

You're aware that you have two declarations of user_notes? Once using var in the inside the click method and again as a parameter in the first ajax. The first one remains undefined, the second is only defined if the success method is called with a defined parameter.

Careful about redefining a name in nested scopes, it's confusing.

Change that first, then if the value of parameter to the success method is what you want, you should explicitly save it to a variable.

(Personally I would not write that nested code. I'd probably use an object with a variable to store the data and a that=this-reference and have thin inline function wrappers on the ajax success and failures that just call object member methods. I like to avoid deep nesting of scopes, and to avid having to scroll horizontally ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.