Ajax readyState returning always 0 - javascript

I've got a problem with this Ajax code, is returning 0 everytime I access 'readyState'. Don't know what the source of the problem is yet, any help would be appreciated:
var xhr = null;
function performAjax(inputUrl){
// instantiate XMLHttpRequest object
try{
xhr = new XMLHttpRequest();
alert("XMLHttpRequest");
}
catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// handle old browsers
if( xhr == null ) {
alert("Ajax not supported by your browser");
return;
}
// get the URL
var url = inputUrl;
alert(inputUrl);
// get Ajax answer
xhr.onreadystatechange = handler();
//alert(xhr.readyState);
xhr.open("POST", url, true);
xhr.send(null);
}
function handler() {
alert("Handler: " + xhr.readyState + " Status: " + xhr.status);
// handle only loaded requests
if(xhr.readyState == 4) { // state 4: that data has been received
alert("here");
if(xhr.status == 200) {
alert(xhr.reponseText);
}
else alert("Error with Ajax");
}
}

You're assigning the handler function incorrectly:
xhr.onreadystatechange = handler; // <--- THERE SHOULD BE NO PARENTHESES
When you include the parentheses, you're asking that the function be called. Without them, you're merely referring to the function, which is what you want.

Related

Get XMLHttpRequest respond for every data received

I'm trying to make a script that will return a respond when data is received on the current page. (New Data Received > Log its content to the console)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
}
xhr.prototype.open = (function(fopen){
return function(){
console.log("Data received.");
return fopen.apply(this,arguments);
}
})(XMLHttpRequest.prototype.open);
The above script is this script. (source)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
Combine with this script. (source)
XMLHttpRequest.prototype.open = (function(fopen){
return function(){
console.log("Data received.");
return fopen.apply(this,arguments);
}
})(XMLHttpRequest.prototype.open)
I wanted to know what I did wrong and how to make it work. Thanks!
You're assigning to the prototype property of your instantiated object, not to the prototype of XMLHttpRequest. You might want to change XMLHttpRequest.prototype.onreadystatechange instead:
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
set: function(listenerFn) {
this.addEventListener('readystatechange', function(...handlerArgs) {
if (this.readyState == XMLHttpRequest.DONE) {
// Custom action:
// console.log(xhr.responseText);
console.log('Detected a new response');
// Run the previous callback that was passed in:
listenerFn.apply(this, handlerArgs);
}
});
}
});
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stacksnippets.net');
xhr.onreadystatechange = () => console.log('handler running');
xhr.send();
This isn't completely in line with the spec of course, this is just an example monkeypatch one might start with. (Mutating the built-in objects like XMLHttpRequest.prototype is bad practice, though - consider avoiding it if possible)
This will log all xhr request
XMLHttpRequest.prototype.send = (function(fsend){
return function(){
this.addEventListener('load', function(){
console.log("Data received.", this.response)
}, {once: true})
return fsend.apply(this, arguments);
}
})(XMLHttpRequest.prototype.send);
xhr = new XMLHttpRequest
xhr.open('GET', 'https://httpbin.org/get')
xhr.send()

What is the best way to do long polling in AJAX requests in JavaScript without JQuery?

hi after searching in the net about how to use the long polling in JavaScript I ended up with three ways, they are mentioned here briefly,but they are implemented using JQuery. I am confused which one to use in case that the AJAX request that I send to the server is asynchronous GET request ,and I don't know how many time it could take.
here is an example AJAX request:
function asynchGETRequest(method,url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("ok");
}
};
xhttp.open(method, url, true);
xhttp.send();
return (xhttp.responseText);
}
var clientFunctions={
getAnswers : function(callback){
var res=asynchGETRequest("GET", "http://localhost:9000/answers");
callback(JSON.stringify(res));
}
}
clientFunctions.getAnswers (function(){
//do some code here after the ajax request is ended
});
can some one guide me please?
I think I found the solution here
function loadFile(sUrl, timeout, callback){
var args = arguments.slice(3);
var xhr = new XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback.apply(xhr, args);
} else {
console.error(xhr.statusText);
}
}
};
xhr.open("GET", url, true);
xhr.timeout = timeout;
xhr.send(null);
}

Overriding a variable within another function JS

Is it possible for me to call a function then override the contents of the variable before actually running it?
So I have a function that basically pulls in my Git profile like this:
var GetGitInfo = function() {
var xhr = new XMLHttpRequest();
var gitURL = "https://api.github.com/users/myself/repos";
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
Then I call the function in another step by doing GetGitInfo(); which all works fine.
However, If I wanted to call the function and replace the gitURL variable how would I achieve that?
So something like
GetGitInfo(
gotURL= "https://api.github.com/users/new_user/repo";
);
You can't modify a local variable to a function from outside the function. They are private to the function's implementation.
But, since it's your own function, you can just create an argument that can be passed into the function. You can even make the argument optional so it will take your initial value as the default value if it is not passed.
var GetGitInfo = function(url) {
var xhr = new XMLHttpRequest();
var gitURL = url || "https://api.github.com/users/myself/repos";
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
Then, you can use the function the way you were using it or you can pass in an URL to use:
getGitInfo(); // uses your default URL
getGitInfo("http://someURL"); // uses the URL you pass in
FYI, this function looks like it will ultimately need to either return a promise or accept a callback so you can communicate the results back to the caller.
From the snippet above you need to set the url as a function parameter so when calling it uses the specified url.
var GetInfo = function(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
GetInfo("https://api.github.com/users/myself/repos");
You should do a toString() on the function:
GetGitInfo.toString()
Then you should do a text search and replace on the variable and it's data:
GetGitInfo.toString().substring(0,GetGitInfo.indexOf('somestring'))+'gitUrl="newURL"'+GetGitInfo.toString().substring(.......)
Then you should eval that string!
Or, you know, use function parameters. Either way. Whatever's easiest.
Pass a parameter to the function:
var GetGitInfo = function(gitURL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
GetGetInfo("https://api.github.com/users/myself/repos");
Just add a parameter to your function:
var GetGitInfo = function(gitURL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
and call it like this:
GetGitInfo("https://api.github.com/users/myself/repos");
Use the parameters
var getData = function(url){
// url can be used here
}
var data = getData("http://apiurl.xy")

Getting undefined in javascript when calling ajax

function get_request(url) {
var request = new getXMLObject();
request.onreadystatechange = function () {
if (request.readyState == 4) {
alert(request.responseText);
var data = eval('(' + request.responseText + ')');
alert(data);
return data;
}
}
request.open("GET", url, true);
//alert(document.getElementById('energy').innerHTML);
request.send();
}
function loadjobs() {
var url = "loadjobs.php?tab=1&id=1111";
//var data=
//alert(check());
alert(get_request(url));
//alert(data);
}
When i m getting data in json format...i am gettin NULL in alert(get_request(url));
while i m getting in alert(data);
Help me
This is because the request in asynchronous . The get_request(url) function does to return anything and hence the null ( although I think it should be undefined and not null ) .
The onreadystatechange function gets called later in the time , when the AJAX request has been completed and the data is returned from the server and hence the alert there works .
This is a misunderstanding of how AJAX works. Ajax is asynchronous. The onreadystatechange function will be called after loadjobs(). The "return path" you are specifying can never work. get_request() will never be able to return the fetched value.
You have two options. Either make the script synchronous - this can be done but is not recommended because it can freeze the browser.
Or, better, handle everything you need to do inside the onreadystatechange callback.
Well, it's an asynchronous call. You will receive the data of request your after get_request has already returned. That means your request.onreadystatechange = function () will be executed long after alert(get_request(url)); is already finished. This means get_request will not be able to return any data from the AJAX call. That's what you have the request.onreadystatechange callback function for, to execute code at an undefined later time when you received the response.
The problem is that Ajax requests work asynchronously. So you can't return the data right away. The way you should do it is to specify a callback function which will handle the response data.
function handleJSON( data ) {
// ...
// do whatever you want to do with the data
}
ajax( "url/file.php?param=value", handleJSON );
////////////////////////////////////////////////////////////////////////////////
function getXmlHttpObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4) {
// onError
if (this.status != 200) {
if (typeof onError == 'function') {
onError(this.responseText);
}
}
// onSuccess
else if (typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}​

Ajax readyState always 1

I'm tying to do what seems like a simple ajax but can't get it to work. Here's my code:
var xmlHttpRequest;
function processRequest(){
alert("process request called with " + xmlHttpRequest);
if(xmlHttpRequest.readyState==4){
alert("status = " + xmlHttpRequest.status);
if(xmlHttpRequest.status == 200){
}
} else {
alert("process request no luck readyState = " + xmlHttpRequest.readyState);
}
alert("process request exiting");
}
function updateCount(customerID, productID) {
xmlHttpRequest = init();
function init(){
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support AJAX!");
}
}
xmlHttpRequest.open("GET", url, true);
xmlHttpRequest.onreadystatechange = processRequest();
}
Like I said in the subject line, readyState is always 1. What am I doing wrong?
Thanks!
Eddy
You are calling processRequest before you start your request.
xmlHttpRequest.onreadystatechange = processRequest();
is wrong and has to be
xmlHttpRequest.onreadystatechange = processRequest;
This will store a reference to your method instead of calling it directly.
As soon as the ready state changes, the xmlHttpRequest object trys to call this reference.
Add xmlHttpRequest.send(); after xmlHttpRequest.onreadystatechange = processRequest;.

Categories

Resources