Working with AJAX & JQuery Mobile

If you are working with JQuery Mobile, one of the most frustrating things can be loading data via ajax only to see it unformatted after the page has been executed….

If you are working with JQuery Mobile, one of the most frustrating things can be loading data via ajax only to see it unformatted after the page has been executed. JQuery uses timing stages to fire events when it loads. When a page is loaded into the DOM (If you dont know what this is, look it up, its one of the most important pieces of information you will ever need), 2 events fire. The first as you might expect is the pagebeforeload call. The 2nd event will be triggered by the success or failure of the previous, either pageload or pageloadfailed. If you are binding any event to an element on the page, the next call to be aware of is the pagebeforechange call. This will fire immediately before the event you called. Not going to get into all the reasons why you can use this to your advantage but I will do a post on this one call individually in the near future because it has some major advantages. If you need to initiate a function AFTER the page is loaded into the DOM on a transition or event call, use the pagechange event. This will fire immediately proceeding that and after all transitions have been completed.

Page Initialization Events

If you are wanting to load or perform events on a page specifically as the page is initialized, there are a few times you can insert your requests. Most developers use the document.ready calls but there are many more uses of page initialization scripting in JQuery Mobile.

pagebeforecreate

$(document).bind(‘pagebeforecreate’)

This will fire off events immediately before the page is loaded into the DOM or initialized. Lots of good uses for this. pagecreate

$(document).bind(‘pagecreate’)

This will fire immediately after the page is loaded into the DOM.

pageinit

$(document).bind(‘pageinit’)

This is really what you should use instead of document.ready when dealing with jQuery Mobile. It fires after everything on the page loads completely. THis is the call i would use to store binding events used on the page. Dont forget to reinitialize the events that are bound if you do use AJAX. I wont get into the .ajaxComplete() method in jquery for this post but in a future post I will more specifically.