Model359
Model359

Reputation: 1

How can I access a variable set in the same function

I am trying to create a sortable list and then pass that to my controller in Codeigniter. I can see that the variable gets set, but when I try to access it from the .submit(function) it isn't there.

Here is the code. I am setting postData and trying to access it later. Thanks for you help:

<script>
$(window).load(function() {
var postData = '';
    $( "#sortMe" ).sortable({
        update: function(event, ui) {
            var postData =  $(this).sortable('toArray');
            $( "#sortMe" ).disableSelection();
            //$.post("do_finishcreate", {var: postData}); 
        }
    });

    $( "#draft_order" ).submit(function( event ) {
        var draftData = postData;
        console.log(draftData);
        alert ("test" + draftData);
        event.preventDefault();
    });
});

</script>

Upvotes: 0

Views: 63

Answers (2)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

The problem is that you are again intialising var postData inside $( "#sortMe" ).sortable which is making postData as local variable instead of global variable,as you are making postData as global so don't intialise it again and correct your code as shown below :-

$( "#sortMe" ).sortable({
     update: function(event, ui) {
     postData =  $(this).sortable('toArray');  //<----- change here
     $( "#sortMe" ).disableSelection();
    //$.post("do_finishcreate", {var: postData}); 
   }
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

The problem is since you have used var postData in the update handler, it becomes a local variable and will be accessible only inside the update handler.

One possible solution is to remove the var from the update handler so that you can update the closure variable declared in the window.load handler.

But I think there is no need to use that too... you can just read the value in the submit handler like

$(window).load(function () {
    $("#sortMe").sortable({
        update: function (event, ui) {
            $("#sortMe").disableSelection();
            //$.post("do_finishcreate", {var: postData}); 
        }
    });

    $("#draft_order").submit(function (event) {
        //read in the submit handler, no need to do it in the update hadnler
        var draftData = $('#sortMe').sortable('toArray');
        console.log(draftData);
        alert("test" + draftData);
        event.preventDefault();
    });
});

Upvotes: 1

Related Questions