XMLHttpRequest not well-formed in Firefox - javascript

I have this code to form get XMLHttpRequest:
var makeRequest = function () {
var xmlhttp = getXmlHttp();
var params = 'name=' + encodeURIComponent('123') + '&surname=' + encodeURIComponent('surname')
xmlhttp.open("GET", 'site.html?' + params, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null)
}
And I have this cross-browser function:
getXmlHttp = function () {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
makeRequest()
All code is in the local file. No server side.
But Firefox says in console this:
'not well-formed'
So what's wrong?
UPD: I have added this xmlhttp.overrideMimeType("text/html");
It doesn'throw an error now but i still can't see it in a web inspector in a firefox
But i can see it in chrome.

It might help if you specified the MIME type.
xmlhttp.overrideMimeType("text/html");
or maybe site.html really is incorrectly formed - check opening tags, closing tags, etc...

Related

Can't send XMLHttpRequest/XDomainRequest in IE8, fails on xhr.send()

I've looked through answers but can't seem to find one that fixes this particular problem. Also a similar question is still unanswered.
I am using IE8 to send a XMLHttpRequest but it never gets sent. IE8 supports XMLHttpRequest objects, so why isn't it sending? (I can't use jQuery for this.)
My code:
window.onload = function() {
// Create the HTTP object
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
alert("couldn't load data");
}
var dataUrl = "./data2.json";
alert("sending");
xmlhttp.open("GET", dataUrl, true);
alert("sent");
xmlhttp.onreadystatechange = function() {
//ready?
if (xmlhttp.readyState != 4)
return false;
//get status:
var status = xmlhttp.status;
//maybe not successful?
if (status != 200) {
alert("AJAX: server status " + status);
return false;
}
//Got result. All is good.
alert(xmlhttp.responseText);
return true;
}
xmlhttp.send(null);
}
The alert('sent'); never gets called, but alert('sending'); does. How can I make this xmlhttp request work?
Edit: I've updated my code to include XDomainRequest for IE8. This gets me past the xmlhttp.open part, but now I'm getting an "Unspecified error" on the xmlhttp.send part.
edited code (Note: I changed my variable name from xmlhttp to xhr.):
window.onload = function() {
// Create the HTTP object
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
alert("couldn't load data");
}
var dataUrl = "./data2.json";
alert("sending");
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Safari
xhr.open('get', dataUrl, true);
}else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open('get', dataUrl);
alert("opened");
} else{
alert('CORS not supported');
};
xhr.onprogress = function () { };
xhr.ontimeout = function () { };
xhr.onerror = function () { alert('error'); };
xhr.onload = function() {
alert(xhr.responseText);
}
setTimeout(function () {xhr.send();}, 0);
}
alert('error'); gets called.

Is there a way to block my JS code until the XMLHttpRequest response arrives?

I'm trying to import some data through a PHP file with this function:
sendJsonRequest("initial", startID);
json = JSON.parse(request);
function sendJsonRequest(type, id) {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
request = xmlhttp.responseText; //writing the response in an already defined variable
}
}
xmlhttp.open("GET","../RequestHandler.php?"+type+"_"+id,true);
xmlhttp.send();
}
The import of the data works very well. My problem now is that I want to use my request right after calling this function, to which point it's still not available (I realized this happens because onreadystatechange runs as function independently), therefore I have to put in some delay until it is so. I find the use of setTimeout or setInterval very uncomfortable, since those aren't blocking the code and I had to refactor some of my code very badly and inefficient. That's why I was looking for a way to modify/block out the function at its end, until the request is available, but neither using an empty while-loop nor the wait/pause/sleep-functions are recommended. Can anybody figure out another way to accomplish this?
Could you just pass a callback?
function sendJsonRequest(type, id, callback) {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
request = xmlhttp.responseText; //writing the response in an already defined variable
if(callback) {
callback(request);
}
}
}
xmlhttp.open("GET","../RequestHandler.php?"+type+"_"+id,true);
xmlhttp.send();
}
and use it like:
sendJsonRequest("initial", startId, function(req) {
var json = JSON.parse(req);
});
Try utilizing Promise
var sendJsonRequest = function sendJsonRequest(type, id) {
return new Promise(function (resolve, reject) {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
request = xmlhttp.responseText;
resolve(request);
}
}
xmlhttp.error = reject;
xmlhttp.open("GET","../RequestHandler.php?"+type+"_"+id,true);
xmlhttp.send();
}
sendJsonRequest("initial", startID)
.then(function(data) {
// do stuff
var json = JSON.parse(data);
console.log(json);
}, function err(e) {
console.log(e);
});

AJAX Call from Javascript does not work the first time but works each successive time

I am using an AJAX call within a javascript function to populate a SELECT input. This script does not work the first time but works as I intend it to each subsequent time that it is called. The relevant code follows:
function getXMLHttp()
{
var xmlHttp;
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function populateEntries(menu, userName, entryRow)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200) && (xmlHttp.responseText == ""))
{
window.alert("There are no records to view!"); }
else if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
{
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "getUsers.php", true)
xmlHttp.send(null);
ADDITIONAL UNRELATED CODE FOLLOWS ....
}
I've checked to see if the "response" is being passed from the AJAX call during the first function call and it is but it is not being passed out of the function for further use in the code that follows except on subsequent function calls. Can anyone tell me why this is happening? Your help will be very much appreciated. Before you tell me that this can be done with jquery, please understand that I need to do it with javascript.

Ajax with php, getting status 200 but readyState 0

Script:
function ajaxHandler() {
var xmlhttp;
try { // Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
} catch (e) { // Internet Explorer Browsers
try {
alert("paososdao");
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { // Something went wrong
alert("Your browser broke!");
return false;
}
}
}
xmlhttp.onreadystatechange = useHttpResponse();
xmlhttp.open("GET","prova.php",true);
xmlhttp.send(null);
function useHttpResponse(){
if (xmlhttp.readyState < 4) // while waiting response from server
document.getElementById('test').innerHTML = "Loading...";
else if (xmlhttp.readyState === 4) {
if (xmlhttp.status == 200 && xmlhttp.status < 300)
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
}
}
I'm testing it using xampp and I always get readyState = 0 and no response from prova.php, but if I open the developer console on Chrome I can see that the GET request status is 200. What's the problem.
Try that:
xmlhttp.onreadystatechange = useHttpResponse;
You're calling the useHttpResponse before you need it.

XMLHttpRequest and setRequestHeader in IE returns an error

I try to make Cross Domain POST requests and get back JSON encoded responses,
everything works fine except in IE 7, 8, 9.
I have try those solutions but i get this error:
Object doesn't support property or method 'setRequestHeader'
Function createXMLHTTPObject() - attempt 1
function createXMLHTTPObject() {
var xmlhttp = false;
var is_IE = window.XDomainRequest ? true : false;
if (is_IE) {
xmlhttp = new window.XDomainRequest();
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
Function createXMLHTTPObject() - attempt 2
var XMLHttpFactories = [
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject("Msxml2.XMLHTTP") },
function() { return new ActiveXObject("Msxml3.XMLHTTP") },
function() { return new ActiveXObject("Microsoft.XMLHTTP") }
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0; i<XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch(e) {
continue;
}
break;
}
return xmlhttp;
}
Function send()
Here it returns the error, at: req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
function send(postData, callback) {
var url = 'http://domain.com/ajax-processing.php'; //url overlap
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method, url, true);
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
if (postData) {
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
console.log('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
Here i call the send function
var insert = 'id=1&type=insert';
CLib.send(insert, function(data) {
console.log(data);
});
Is it possible to make Cross Domain requests in IE?
How i can leave behind this part, without using any other library like jQuery?
Thanks a lot #Esailija who inform me that i can't make set request headers with the XDomainRequest.
So i tried other methods and solutions also and i finally came back with a simpler method:
changed the POST requests to GET and everything working fine after some small changes.

Categories