6

So, I'm loading some data from a MVC3 action that returns Json, containing some parameters and content as a string. I append the content to some div. In the partial view I have a document.ready JQuery event. For some reason that function executes before the content is appended and all the selectors I declare in the ready function are empty.

Is there a logic reason for this? Is I set a timeout the selectors see the elements. But a timeout can be very imprecise.

Any suggestions?

Thanks!

Example code fiddle: http://jsfiddle.net/aKxy7/

Luis Aguilar
  • 4,331
  • 6
  • 36
  • 55

6 Answers6

3

It sounds like you are expecting $(document).ready() to fire after all assests are loaded. That's not how $(document).ready() works. It is triggered when the DOM is finished rendering. Nothing more. It sounds like you want to use $(window).load(), which does wait until all assets are loaded.

robsch
  • 9,358
  • 9
  • 63
  • 104
Alex
  • 64,178
  • 48
  • 151
  • 180
0

$(document).ready() gets called when the HTML! is loaded. This means that if your HTML loads some javascript that makes changes to the HTML DOM, those $(document).ready() gets called before that.

You should either make sure your function is called last or use setTimeout that calls itself untill the elements you need are all loaded.

Khez
  • 10,172
  • 2
  • 31
  • 51
0

In your $(document).ready function you can call jQuery's $.ajax or $.getJSON to get the answer from your server. Then you can inject the json response where you want. No setTimeout needed

James Kyburz
  • 13,775
  • 1
  • 32
  • 33
0

$(document).ready in ascx page after ajax callback

I had the same issue.

Community
  • 1
  • 1
Ayo
  • 1,198
  • 2
  • 16
  • 36
0

First off,

var elementIWannaGet = $('html-content-div');

should be

var elementIWannaGet = $('#html-content-div');

However, what you may be better off doing is separating the script from the content, as the dom is already loaded...

Consider changing the response to this:

{ result: true,
  data: { id: '1' },
  elementId: '#html-content-div',
  content: '<div id="html-content-div">Html content! :D</div>'
}

And then change your contentLoaded handler as follows:

function contentLoaded(response) {
    if (response.result == true)
        handleError(response);

    // Get the container where the response.content will be rendered to.
    var targetContainer = $('#target-container-id');

    // Append the content
    targetContainer.append(response.content);

    // Do something with your container
    alert( $(response.elementId).html().length );
}
Ron DeFreitas
  • 629
  • 3
  • 12
0

I ended up coding a method that waits until a selected element in the HTML loaded via ajax is ready.

Luis Aguilar
  • 4,331
  • 6
  • 36
  • 55