views:

106

answers:

2

I have this js code:

$("#startSearch").live("click", function(event) {
    $("input:checkbox[name='searchId']:checked").each(function() {
        var searchId = $(this).val();
        var host = '';
        $.post("php/autosearch-get-host.php",{sId: searchId},function(data){
            host = 'http://' + data + '/index.php';
        });
        //alert(host);
        $.getJSON(host,{searchId: $(this).val()},function(){
            pagination("php/pagination.php", $('#currentPage').val(), $('#sortBy').val(), $("#sortMode").val(), "autosearch");
        });
    });
});

The php file php/autosearch-get-host.php returns a string with the host name. What I want is to get the host from the database, create the URL using string concatenation and pass it as an argument to another $.post. $.post should use that URL like this:

$.getJSON(host,{searchId: $(this).val()},function() {
    pagination("php/pagination.php", $('#currentPage').val(), $('#sortBy').val(), $("#sortMode").val(), "autosearch");
});
A: 
$("#startSearch").live("click", function(event){
  $("input:checkbox[name='searchId']:checked").each(function(){
    var searchId = $(this).val();
    var host = '';
    $.post("php/autosearch-get-host.php",{sId: searchId},function(data){
      // this code is executed when the POST is finished
      host = 'http://' + data + '/index.php';
      $.getJSON(host,{searchId: $(this).val()},function(){
        pagination("php/pagination.php", $('#currentPage').val(), $('#sortBy').val(), $("#sortMode").val(), "autosearch");
      });
    });
  });
});
Fábio Batista
A: 

Try moving that one request inside the callback function. As ajax request are asynchronous the variable host will be still set to '' when $.getJSON is called

$("#startSearch").live("click", function(event) {
    $("input:checkbox[name='searchId']:checked").each(function() {
        var searchId = $(this).val();
        var host = '';
        $.post("php/autosearch-get-host.php",{sId: searchId},function(data){
            host = 'http://' + data + '/index.php';
            $.getJSON(host,{searchId: $(this).val()},function(){
                pagination("php/pagination.php", $('#currentPage').val(), $('#sortBy').val(),  $("#sortMode").val(), "autosearch");
            });
        });
    });
});
jitter