Judson
Judson

Reputation: 107

Populating pages using ajax data within jquery-mobile not always working

I am using a url variable in my links to pass a unique ID, which is run through ajax and injected using .html(). See code below

I have added a timeout, added empty() to the div before populating,

LINK TO PAGE:

<a href="member.html?id=' + member.id + '" data-role="none" data-transition="slide">

PAGE CREATION:

$(document).on( "pageshow", "#member-page", function(event) {
   .....
   var request = $.ajax({
      url: serviceURL + 'member_profile',
      method: "GET",
      data: { id : id },
      dataType: "html"
   });
   request.done(function( data ) {
      ...
      alert(html);
      $('#member-profile').hide().empty().html(html).fadeIn();
    });


    request.fail(function( jqXHR, textStatus, errorThrown ) {
       alert( "Request failed Line 752: " + textStatus + " - " + jqXHR.responseText);
       $.mobile.loading( "hide" );
    });
});

Sometimes it works and sometimes it doesn't. Eventhough the alert(html) always shows data.

Is there a better way to pass the id, and to render the page, like using pagebeforecreate

Upvotes: 0

Views: 78

Answers (1)

Gajotres
Gajotres

Reputation: 57309

You missed to show us the most important part of your code. It would be so much easier to analyze your code if you have also included $.ajax section.

I would presume two possible solutions, also I think both of these solutions are entwined in your case.

  • Ajax process in asynchronous in nature, which means the rest of the code will not wait for it to finish. This may be the reason why you sometimes see your new content and sometimes not. It is probably related to the speed of AJAX call.

Have you tried to do it like this:

$.ajax({
  url: "YOUR ENDPOINT"
}).done(function(html) {
  $('#member-profile').hide().empty().html(html).fadeIn();
});

This way content will be cleaned/filled only when it is actually received.

  • The second possibility is pageshow event itself. Depending on its speed, jQuery Mobile may or may not have time to prerender new HTML content and show it. If this is he case it would be better to use pagebeforecreate or pagecreate event. Or pageinit if you are using older jQuery Mobile events.

Upvotes: 1

Related Questions