Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass parameter from $.post() callback to outer variable

Tags:

jquery

ajax

php

basically i want to hold a parameter that retrieve value from $.post() call like this:

init = function(){          
var lastpage = getLastPage();
}

        function getLastPage(){
            $.post("getInfo.php",{ 
                last: "yes"
            },
            function(data){
                setLast(data.last);
            },'json');

            return function setLast(data){
                return data;
            }
        }

so when reach at last post (last page) i should check with lastpage variable that has a value returned from getLastPage() function.

I'm pretty blur with javascript pointer and all. Please help guys.

update (20/4/2010):

I've done the other way around, like this:

init = function(){            
  getLastPage();
  if((page+1) == $("#lastpage").val()){
     alert("this is last post");
  }else{
     page++;
     //get info and display to the page here
  }
}
     function getLastPage(){
        $.post("getInfo.php",{ 
            last: "yes"
        },
        function(data){
            $("#lastpage").val(data.last);
        },'json');
    }

first run the function to temporarily store the value in hidden input tag (lastpage) and then grab the value again to check it whenever i click forward button.

if you all have more appropriate way please tell me.

like image 249
Nazrul Muhaimin Avatar asked Aug 24 '26 23:08

Nazrul Muhaimin


1 Answers

You should change your code around like this:

$.post("getInfo.php",{ last: "yes" },
  function(data){ 
    functionToRunAfterYouHaveDataSometimeLater(data.last); 
  }
,'json');

The problem with your overall approach is that with AJAX, you're dealing with an asynchronous operation. This means that the function(data) { } portion doesn't run then, it runs later, so your return doesn't actually return anything, it'll be undefined.

Instead of this approach, you need to call $.post() then call whatever function relies on this data to continue as part of $.post()'s callback. After doing that your code order looks like this:

  • $.post() executes, firing off a request to the server
  • The rest of your code after $.post() runs
  • Later when the response comes from the server and you have data, your callback executes
  • Now continue to do what you need with that data
like image 163
Nick Craver Avatar answered Aug 26 '26 13:08

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!