-1

I have to use $.post function of jquery several times in a page. Also I have to use the returned data from post method for filtering purpose. So I put the post function like this:

$(document).ready(function(){
function loadData(url){
$.post(url,function(data){
var $data = data;
});
}

var raw = loadData(page01.php).filter("#someId").html();
$("#content").html(raw);

var raw = loadData(page02.php).filter("#anotherId").html();
$("#content2").html(raw);
});

But it is not working. Any help to modify the above code for working will be appreciated. Regards

stockBoi
  • 287
  • 2
  • 9
  • 26

1 Answers1

1

You can't magicaly call another method after your function just like in jquery loadData('page02.php').filter your function need to return jQuery object for this to work, in your case your loadData function don't return anything. But you can't return jQuery object since it's aynchonous call. If the content returned by the server is html then to modify that html you need to add callback function because it's the only way to apply something after ajax call.

Your code should look something like this:

$(document).ready(function(){
    function loadData(url, callback) {
        $.post(url, function(data){
            callback($(data)); // not sure if jquery detect if the content is 
                               // html here, if yes then you can remove $( )
        });
    }

    loadData('page01.php', function(html) {
        var raw = html.filter("#someId").html();
        $("#content").html(raw);
    });

    loadData('page02.php', function(html) {
        var raw = html.filter("#anotherId").html();
        $("#content2").html(raw);
    });
});
jcubic
  • 61,973
  • 54
  • 229
  • 402