Sunday, April 15, 2012

JQuery Mobile - Ajax Linking and Markup


This little error had me stumped for a couple of days, jQuery Mobile was throwing errors every time I tried to load a page via Ajax, which is the normal procedure with links in jQuery Mobile as you can see from theDocumentation.
These are the kind of errors I was getting
Break on Error to.data(“page”) is undefined
Line 8730 (Pulled from github 19/01/2011)
//trigger before show/hide events
from.data(“page”)._trigger(“beforehide”, {nextPage: to});
to.data(“page”)._trigger(“beforeshow”, {prevPage: from});
and
Uncaught TypeError: Cannot call method ‘_trigger’ of undefined
transitionPagesjquery.mobile.js:8732
$.mobile.changePage.$.ajax.successjquery.mobile.js:8878 jQuery.extend.handleSuccessjquery.mobile.js:6172
jQuery.extend.ajax.onreadystatechange.xhr.onreadystatechange
The only way I could get a page to load was to apply a rel atrribute to the link with the value ‘external’, like so:
<a rel="external" href="multipage.html">Multi-page link</a>
(Thanks for the heads up rigoxls)
But this defies the purpose and princeables of the jQuery Mobile framework, you can read about the navigation model they use here. So instead I decided to butcher everything in my initial loading page, removing everything I thought could or might be causing these errors (jCarousel, all Ajax calls, I even directly copied the example markup from the docs)
Everything I tried failed and I still got this damn error until I had the brainwave that it might be the returned content from the link that may be causing the error.. I was right.

The Fix

As it turns out the page you are linking too needs to be formated correctly, I.E like the following (I’m not sure if the Javascript is needed however I’ve left it in)
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" />
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>Page Title</h1>
</div><!-- /header -->
<div data-role="content">
<p>Page content goes here I AM THE LINK CONTENT WOO</p>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /header -->
</div><!-- /page -->
</body>
</html>

No comments:

Post a Comment