I am trying to redirect one page to another using jQuery/ajax
. Here I am using php
as server side.
This is how I send data to js:
$url = 'index.php?p=dashboard';
// print the message to Ajax:
$messages = array('success'=>true,'pageRedirect'=>$url);
echo json_encode($messages);
This is how I handle the response in AJAX
var request;
$("#login").on('submit', function(e) {
e.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "user_processing.php",
type: "post",
data: serializedData,
success: function(json) {
json = jQuery.parseJSON(json)
if (json.success) {
setTimeout(function() {
$(window).attr('location',json.pageRedirect);
}, 500);
}
}
});
request.always(function () {
$inputs.prop("disabled", false);
});
});
My problem is, above everything works properly in firefox
and chrome
, but this redirection is not working in iphone
and safari
browsers. Hope somebody may help me out.
Tested the following in an iPhone emulator:
window.location.href = "google.com"
And it complains about a Malformed URL:
Running
window.location.href = "http://google.com"
works.
Basically you will need to look into the errors you receive, be it with iPhone or Safari. If you still have a problem with this feature, then you might want to edit your question and add valuable information, such as the error messages you get.
EDIT
I discussed this issue with @ugsgknt in private and even after the fix we have managed to reproduce the problem using an iPhone Safari, and used server-side logging (by posting any errors that would occuron the server) to find out what the issue is.
It turned out that the form was being posted by the browser for iPhone Safari, even though the code the asker has written was very explicitly calling preventDefault
.
I have proposed a work-around for this and, as far as I know, it is being implemented at the time of this writing:
It is imperative to find out whether the Javascript is loaded by iPhone at all and to find out what prevents it from being executed. If the problem reproduces with a Macbook, then the asker needs a Macbook for the time being to easily reproduce and fix the problem. If not, then a proper iPhone emulator that provides console output is needed.
It is possible that something as simple as refactoring the HTML not to use a form
tag and use something else instead might help. That at least would prevent the browser from posting. But the real question is: why is Javascript not being executed at mobile Safari. Maybe Javascript is running there and failing for some reason earlier than defining the form post event listener. Or, maybe the file is not even loaded for such a device. There could be many possible causes and the asker will need a proper dev environment in order to detect the exact issue.