Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12367

Function does not work properly if not nested in another function

Sorry for unclear title but I couldn't find anything that could suit my problem.To better explain what it is let me show you my javascript code:

function askForIDForCommand()
{
  var content;
  $.post("Somepage.aspx", function (data)
  {
     content = $(data).find("#myDiv").html();
  });

  var myFunc = function () { }
  var buttons = [{ text: 'OK', click: myFunc}];
  ui_window("Hi", 630, content, buttons);
 }

As you can see I declare a variable called content. Then I assign the html of a specified div to it. And then I send it to ui_window function which just displays a jquery dialog with the specified content. The problem is I don't get that html content in the dialog. When I look up the value of "content" with Firebug I can see that it contains html content. What makes me desperate is if I change the above function to the below one the html content gets displayed in the dialog:

    function askForIDForCommand()
{
  var content;
  $.post("Somepage.aspx", function (data)
  {
     content = $(data).find("#myDiv").html();
     var myFunc = function () { }
     var buttons = [{ text: 'OK', click: myFunc}];
     ui_window("Hi", 630, content, buttons);
  });

 }

In case you can't notice the difference, I just put the call of ui_window inside the $.post() method. And it works. Why's that?

And here's the html content in case you need it:

        <table>
        <tr>
            <td align="right">
                <label>
                    Enter the ID:</label>
            </td>
            <td>
                <input id="txtID" type="text" onkeydown="return onlyNumbers(event);" maxlength="8"/>
            </td>
        </tr>
    </table>

Upvotes: 0

Views: 93

Answers (3)

francadaval
francadaval

Reputation: 2481

The problem is that the inner function is called when you recieve response from server. Then in the first case the variable is not assigned yet when those lines are executed and in the second one you are sure that ui_window is called with available data.

Upvotes: 2

Shimu
Shimu

Reputation: 1147

The problem is the AJAX call to the server. In the first case, you send a request and go straight to the next command, ie myFunc and so. Therefore your content variable isn't initialized at this moment.

Upvotes: 1

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

You're not assigning to content before you call ui_window. That assignment happens inside your anomyous function and therefore is not executed until someone calls that function (that is, once the post to Somepage.aspx is completed).

In contrast, you're calling ui_window() as soon as you have started the post to Somepage, but without waiting for that operation to finish. At that time your completion function still hasn't been called, and therefore content still contains undefined.

Upvotes: 4

Related Questions