I've got this function:
function Ajax() {
var xmlhttp, onready, open, response;
if(window.XMLHttpRequest) {
this.xmlhttp = new XMLHttpRequest();
} else {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
this.onready = function(onready) {
this.xmlhttp.onreadystatechange = function() {
if ( this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
onready.call();
}
}
};
this.open = function(_filename, _method) {
this.xmlhttp.open(_method, _filename, true);
this.xmlhttp.send(null);
};
this.response = function() {
return this.xmlhttp.responseText;
};
}
function rc() {
var ajax = new Ajax();
ajax.onready(function() {
document.getElementById("comments").innerHTML = ajax.response();
});
ajax.open("ab.php","GET");
}
rc();
And the request is sent fine, but i can't extract the response.
It shows that readyState doesn't exist in xmlhttp object.
When I run your code I am getting "this.xmlhttp is undefined" for the line:
if ( this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200)
You are already inside of the xmlhttp object. The line should be:
if ( this.readyState == 4 && this.status == 200)
This should fix the error.
This could be a bug in Firebug, according to this discussion.
What version of firebug are you using?
Can you try
Updating Firebug
Trying the same with another browser? These days almost all browsers have a developer console.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got two functions in Javascript. One gets JSON data from a php file.
{"company_name":"","job_title":"Superhero","unix_time_convert":"Posted 06th of September '18","link":"2"}
The javascript function to return the JSON is this:
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = (this.response);
return data;
//alert( data );
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
Notice that alert( data ); will return the JSON data in a box.
But when I assign the function to a variable elsewhere like so, it returns undefined.
window.onload = function () {
var data = assignJsonData();
alert(data);
}
What am I missing here?
Sorry to ask, I've been on this for hours...
Thanks
Andy
You should use callBack to retrieve data from ajax request , and get data when ajax request is finieshed , your could should look like :
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.response);
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data){
alert(data);
});
}
As Jafar pointed, you should use a callback!
If you want to check the order the things is executed, run the code bellow.
var returnData = "";
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.readyState, this.status);
if (this.readyState == 4 && this.status == 200) {
returnData = this.response;
console.log('enter');
//console.log(this.response);
//return data;
//alert( data );
}
};
xmlhttp.open("GET", 'https://jsonplaceholder.typicode.com/todos/1', true);
xmlhttp.send();
}
assignJsonData();
console.log("returnData: " + returnData);
XMLHttpRequest is asynchronous. You need to either use a callback or a Promise.
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.response
callback(data)
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data) {
alert(data)
});
}
You need to use Promise.
Check - How do I promisify native XHR?
You don't have the data in alert, because the response is not ready I guess.
somehow this code just blanks and isn't really doing anything.
Doesn't even show any errors.
So can Someone help?
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon; //calls the makeAnn() Function
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(){
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}
Somehow it never shows any actual complaints or anything on the console log.
No alerts or whatever.
Doesn't write the data sent to the php or database.
No nothing really.
And I have tried the Php and html, their both fine.
It's just this part of my code that won't work.
You are not calling the function inside your onreadystatechange handler. See below.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
// mycon; //wouldn't do anything
mycon(); // THIS should work better...
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
EDIT:
The other problem which I now noticed is that you are referencing jsonReturn way, way out of its scope.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon(jsonReturn); // pass jsonReturn as a parameter
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(jsonReturn){ // pass in as a parameter
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}
I am trying to parse XML document from java script with the below code
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.responseXML != null) {
Caption(this.video, this.responseXML);
} else {
throw new Error("Can't read resource");
}
};
xhr.video = obj;
xhr.open("GET", "Br001.xml", true);
xhr.send("");
But I am getting status=0 and responseXML = NULL.
FollowUp:
After changing the onreadystatechange as below i am getting readyState=1 and status=0 and responsexml=NULL and getting only one callback
xhr.onreadystatechange = function () {
if (this.readyState == 4
&& this.status == 200) {
if (this.responseXML != null) {
Caption(this.video, this.responseXML);
} else {
throw new Error("Can't read resource");
}
}
};
readyState goes through multiple stages before the response is available. You have to wait for readyState to change to 4:
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.responseXML != null) {
Caption(this.video, this.responseXML);
} else {
throw new Error("Can't read resource");
}
}
};
It's also best to check status (e.g., to make sure it's 200 <= status < 300 (as 2xx are the "ok" responses), although your this.responseXML != null is probably good enough for this use.
I've looked at tons of demos and AJAX and JavaScript tutorials, but I can't seem to get this thing to work right. Here's what I've got...
function createRequestObject() {
var ro = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
ro = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
}
return ro;
}
function ajaxrequest(){
var http = createRequestObject();
if(http) {
var name = "Strassburg";
var message = "Strike three you're out";
http.open('post', '/server/shout.php');
// needed in order for most servers to see POST data
http.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4){
if(http.responseText.indexOf(':' != -1)) {
var data = http.responseText.split(':')
alert(data)
}
}
};
http.send('name=' + name + '&message=' + message);
}
}
Right now I'm doing it with static text (name and message instead of using the user entered fields), but I just get an empty alert. If the readyState is set to 4 this means that the ajax call was successful I believe? the server/shout.php was given to me, I dont understand php very well, but if a snippit of that is needed I can put it here as well.
its this line
http.responseText.indexOf(':' != -1)
( ":" != -1 ) = true, so indexOf is looking for true in the responseText
try this
http.responseText.indexOf(':') !== -1
readyState == 4 means that request was completed, to check if it was OK check http.status == 200
if (http.readyState == 4) {
if(http.status == 200) {
alert(http.responseText);
}
}
P.S. that should be a comment, but i don't have enough rating to comment your post
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.