I have been using this code for a long time successfully:
function doXMLReq(url, data) {
var req = false;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
if (req.overrideMimeType) {
req.overrideMimeType('text/xml');
}
}
req.onreadystatechange = function() { doStuff(req); };
req.open('POST', url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setRequestHeader('Content-length', data.length);
req.setRequestHeader('Connection', 'close');
req.send(data);
}
function doStuff(req) {
if (req.readyState == 4) {
alert(req.status);
if (req.status == 200) {
alert('ok');
}
}
}
The URL submits a post to a PHP script which returns XML. I added in these alerts to do simple testing. Obviously where the alerts are major functionality is placed, and on every desktop browser I reach the "ok" alert after submitting my form. Additionally, if console.log(xml) type statements are issued, I can see that the XML is loaded properly on the desktop browser, and functionality is normal.
For some reason on mobile browsers (safari, android) the req.status alert always has a value of 0
, and the XML data is not returned. If I post a form directly to the URL (instead of using this JS), the browser renders the XML perfectly.
The URL is in the same directory as the original PHP file, on the same domain, etc. The header is set correctly on the PHP form which is passed through URL.
header('Content-type: text/xml');
I am thinking that it may have something to do with https
, since this is the only page which encounters this error, and it is also the only page in the https
domain out of maybe a hundred pages this code is on.
I have also tried to use jQuery's $.ajax
, because many other users in other threads have suggested that the use of jQuery could solve cross-browser woes. I re-wrote my entire PHP script and much of my javascript to accomidate for $.ajax
and I must admit I reduced the code by a meaningful amount, but the XML HTTP request still returns 0
on mobile browsers... here is the code I used:
function doForm() {
var form = $('#i_form');
$.ajax({
type: form.attr("method") || 'post',
url: "fooscript.php",
data: form.serialize(),
dataType: 'xml', //Disables xml autoparsing
success: function(xml){
doXMLback(xml);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(jqXHR.statusText);
}
});
return false;
}
function doXMLback(xml) {
var errors = $(xml).find("errors").text();
var success = $(xml).find("uri").text();
if (errors) {
errmsg = errors.split("|");
errmsg = errmsg[1];
$('#er').text(errmsg);
return false;
}
if (success) {
window.location = success;
}
}
(Obviously above instead of the form being submitted there is a div which has a simple onclick function which calls the doForm()
function)...
How can I get mobile browsers running on 3G/4G to submit to a form and receive XML data back using ajax?