3

I need to load html on to a page via jquery ajax. Then, after the html has loaded, I want to parse it for certain data that will be in the loaded html, and use it to create map markers. So I need the load method to act synchronously, so that the html is definitely loaded before my setMarkers() method tries to parse it.

$.when($("#orders").load("datadisp.aspx")).done(function () {
    setMarkers();
});

I thought the current set up that I have is supposed to do exactly that, but I can tell from the debugger that setMarkers() is still being called before the load has completed, because when I put a breakpoint on setMarkers() and inspect the html after it has hit this breakpoint, I can see that the expected html has not loaded yet. Can somebody show me the right way to solve this problem? Thanks.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

3 Answers3

6

The issue you have is that load() does not return a promise that can be used with $.when. If you want to execute some code after the load() has completed, put it in the callback handler:

$("#orders").load("datadisp.aspx", function() {
    setMarkers();
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

I think you are misusing the jQuery.when(), because that method is part of the Deferred object, which implements the Promise interface, and the jqXHR object returned by jQuery.ajax() implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information)

A better approach could be as follow:

$.when(
  $.ajax({
    type: "GET",
    url: "datadisp.aspx"
    //dataType: "html"
  })
).then(
  function done(data) {
    console.info("done!");
    console.log(data);
    setMarkers();
  },
  function fail(jqXHR, textStatus) {
    console.log(jqXHR);
  }
);

You can just use jQuery.ajax() and transport/handle the jqXHR object: https://stackoverflow.com/a/30848934/2247494

Or you can use the Deferred object with jQuery.when() to handle the Promise interface: https://stackoverflow.com/a/30923089/2247494

Community
  • 1
  • 1
jherax
  • 5,238
  • 5
  • 38
  • 50
0

If you want to load WebForm or Html page then use load and pass function in handler of load and do rest stuff.

$("#orders").load("datadisp.aspx", setMarkers);

/*Handler function*/
function setMarkers(data)
{
/*Code*/
}
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Neo
  • 51
  • 1
  • 3