Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax reloads page instead of performing ajax request in Safari on iOS

Tags:

jquery

ajax

ios

I have a function being called on a page on a local apache instance (/test) which calls a subpage (/test/info) with jQuery.ajax and correctly makes an AJAX call and dynamically loads the content from the response on my desktop in FF, Safari, Chrome, but in the iOS emulator, no call is made and the page is refreshed.

window.getInfo = function ( event ) {
  console.log('1) prior to $.ajax');
  $.ajax({
    url: 'http://localhost/test/info',
    dataType: 'html',
    beforeSend: function(xhr) { 
      console.log('2) beforeSend'); 
    },
    success: function(data, textStatus) {
      console.log('3) success');
      if ( textStatus == 'success' ) {
        // doing stuff with data
      }
    }
  }).always( function() { console.log('4) always'); });
};

From the desktop browsers all of the logs are printed and my apache server reports a request at /test, but on Safari in the iOS emulator, only the '1) prior to $.ajax' and '2) beforeSend' logs are printed and the next request made to apache is for /test.

Does anyone have any idea what is happening here, and how to make iOS behave itself?

UPDATE: When I add the async: false attribute to the ajax call, all the logs are printed, and the request is made, so that basically fixed the issue; however the page still reloads which I believe is a different issue related to event propagation on iOS.

like image 376
bschlueter Avatar asked Jul 16 '13 18:07

bschlueter


1 Answers

All that is needed to make this work is a return false; from the handler function. See event.preventDefault() vs. return false for a more complete explanation, but basically "return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object."

So a fully functional version of the above code is:

getInfo = function() {
  $.ajax({
    url: '/test/info',
    dataType: 'html',
    success: function(data, textStatus) {
      if ( textStatus == 'success' ) {
        // doing stuff with data
      }
    }
  });
  return false;
};

// The order of vv that string may be important
$(document).on('click touchend', '.getInfo', getInfo );
like image 88
bschlueter Avatar answered Nov 15 '22 10:11

bschlueter