Ajax with php, getting status 200 but readyState 0 - javascript

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.

Related

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 - How to get outer function of onreadystatechange function to return 'true'

I have this Javascript/AJAX function:
function submitValidate() {
var xmlhttp;
xmlhttp = null;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
try { xmlhttp = new XMLHttpRequest();
}
catch (e){}
} else if (window.ActiveXObject) {
try { xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e){
try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); // code for IE6, IE5
}
catch (e){}
}
}
if (xmlhttp) {
xmlhttp.open("GET","registerTest.php",true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (xmlhttp.responseText==="true") {
return true;
}
} // if xmlhttp.readyState && xmlhttp.status
}// xmlhttp.onreadystatechange
}// if
return false;
} //submitValidate()
I would like for submitValidate() to return true or false.
However I have come to realize that I cannot just 'return true;' inside the onreadystatechange function as I did here -
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (xmlhttp.responseText==="true") {
return true;
}
} // if xmlhttp.readyState && xmlhttp.status
}// xmlhttp.onreadystatechange
.. if I want submitValidate() to return true in that case.
Can somebody please tell me how I can get submitValidate() to return true if the onreadystatechange function returns true?
Thanks in advance.
Basically you cannot. There are two possibilities for you:
Send a request with parameter async=false and your code will be blocked until the request is not done. This is not user frienldy.
var myReturnValue;
xmlhttp.open("GET","registerTest.php",false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (xmlhttp.responseText==="true") {
myReturnValue = true;
}
} // if xmlhttp.readyState && xmlhttp.status
}// xmlhttp.onreadystatechange
xmlhttp.send();
alert(myReturnValue);
Keep the things as they was, your code will continue to execute while xmlhttp.onreadystatechange will be processed parallelly once the request is done (we can't be sure exactly when this occurs, due to network bandwidth and etc..)

XMLHttpRequest not well-formed in Firefox

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...

what does IE like about the xmlhttprequest?

i have the following code working in all browsers now but IE8.. i read that if i used the xhttp=new ActiveXObject("Microsoft.XMLHTTP"); line it should work for IE but i'm not sure..anyone have experience in getting this to work with ie8
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc = loadXMLDoc("nhl_standings_xml.xml");
var x = xmlDoc.getElementsByTagName("nhlall");
Hmm, the code looks okay. Have you tried an Asynchronous request? When you have xhttp.open("GET", dname, false);, it's synchronous. Change that false to a true, and you're asynchronous. Also, you variable xhttp isn't properly declared (correct me if I'm wrong. Being a Python coder, I can't tell half of the time).
Try this code:
function loadXML(url)
{
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) {
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
return xmlHttp.responseText;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
var xmlDoc = loadXML("nhl_standings_xml.xml");
var x = xmlDoc.getElementsByTagName("nhlall");
i suggest you this MINIMAL ajax engine.
http://pastebin.com/uXJe9hVC
an example of usuage
ajax POST request
Ajax.call('GET','http://localhost/index.php',function(data) {
{
//doing stuff with the data response
},'ASD');
call arguments: URL,callback,POST
this is so easy.
Try this as a request starter:
if (window.XMLHttpRequest) return new window.XMLHttpRequest();
else if (window.ActiveXObject) {
// the many versions of IE's XML fetchers
var AXOs = [
'MSXML2.XMLHTTP.6.0',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP',
'MSXML.XMLHTTP'
];
for (var i = 0; i < AXOs.length; i++) {
try { return new ActiveXObject(AXOs[i]); }
catch() { continue; }
}
return null;
}
The order above should be the correct best-to-worse order, BTW.

Categories