I am trying to get status of any address,in which request_withd function is call ,then action goes on another function named 'is_address_exist' which is return response status of any address in
'yes' or 'no' but i am getting 'undefined' response message in console.
function is_address_exist(address) {
var xmlhttp = new XMLHttpRequest();
var url = '../ withdrawn/address_check/' + address;
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
return xmlhttp.responseText;
}
}
}
}
function request_withd(e) {
var response_status = is_address_exist(address);
console.log(response_status);
}
The onreadystatechange function is a call back function, it runs async, it should have the intended actions included in its definition. This should work.
function is_address_exist(address){
var xmlhttp=new XMLHttpRequest();
var url='../withdrawn/address_check/'+address;
xmlhttp.open('GET',url,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4)
{
if(xmlhttp.status===200){
console.log(xmlhttp.responseText);
}
}
}
}
function request_withd(e){
is_address_exist(address);
}
Or for non async function
function is_address_exist(address) {
var responseText ="";
var xmlhttp = new XMLHttpRequest();
var url = '../ withdrawn/address_check/' + address;
xmlhttp.open('GET', url, false);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
responseText = xmlhttp.responseText;
}
}
}
return responseText;
}
function request_withd(e) {
var response_status = is_address_exist(address);
console.log(response_status);
}
is_address_exist() doesn't return anything here.
Your return is happening within a xmlhttp.onreadystatechange = () => ...
You could either use callbacks or promises here.
Callback example:
function is_address_exist(address, handler){
//...
xmlhttp.onreadystatechange = function(){
//...
handler(xmlhttp.responseText);
});
}
is_address_exist('...', function(data){
console.log(data);
});
Promise example:
function is_address_exist(){
return new Promise(function (resolve, reject) {
//...
xmlhttp.onreadystatechange = function(){
//...
resolve(xmlhttp.responseText);
});
xmlhttp.onerror = reject;
});
}
is_address_exist()
.then(function (data) {
console.log(data)
})
.catch(console.error.bind(console));
Related
How do I retrieve returndata variable outside fn() function?
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
You need to define global variable before function and then store the result into this variable. The way you do it now, is definition of local variable.
var returndata;
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
AJAX requests are asynchronous. You cannot have the pizza before it is baked. In real life you call the pizza company. They bake it and you wait. AJAX is the same. So setting the returndata won't do it all by itself.
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
The readystate function isn't there for nothing. It waits until the request has been processed. From there on you can go on. Every function/script that is depended on the returned data should be called upon from that function.
Still you can do this:
var returndata; //this will now be a global variable.
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
doSomeThing(); //fire depended value.
}
}
xmlhttp.send(vars);
}
function doSomething()
{
if(returndata)
{
//do Something
}
else
{
alert("Data isn't loaded yet");
}
}
Here is my code:
var xmlhttp;
function HttpObject(str)
{
//alert("iam in process request");
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
alert ("xmlhttp");
}
else if(window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert ("ms.xmlhttp");
}
else
{
XmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
xmlhttp.onreadystatechange = processRequest();
xmlhttp.open("POST",'/CountryTest.do',true);
xmlhttp.send(null);
}
function processRequest()
{
if (xmlhttp.readyState === 0) {
alert("u r in 0 :: The request is not initialized ");
}
var target = document.getElementById("curlist");
var res = xmlhttp.responseText;
alert(res);
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
alert("in readystate");
}
else
{
alert("error in readystate");
}
}
It always displaying status 0
curlist is id of my country state prog
can any one say me where is problem?
/CountryTest.do is the url pattern of the servlet.
xmlhttp.onreadystatechange = processRequest();
You just called processRequest immediately, and assigned its return value to onreadystatechange.
You want to assign the function itself, without calling it.
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState=='4')
{
alert(xmlhttp.responseText);
}
}
I'm working on the project where I (sadly) cannot use jQuery. And I need to do something which is simple in jQuery but I cannot do it in pure JavaScript. So, I need to run one ajax request using a response form another one. In jQuery it will look like:
$.get("date.php", "", function(data) {
var date=data;
$("#date").load("doku.php?id="+date.replace(" ", "_")+" #to_display", function() {
$(document.createElement("strong")).html(""+date+":").prependTo($(this));
});
});
And this is my code in pure JS which isn't working:
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(ObiektXMLHttp)
{
ObiektXMLHttp.open("GET", "date.php");
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
var date = ObiektXMLHttp.responseText;
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
}
}
}
ObiektXMLHttp.send(null);
}
What am I doing worng?
You forgot to call ObiektXMLHttp.send(null); on second case:
//....
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function() {
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
};
//Here
ObiektXMLHttp.send(null);
How about something like this (naive prototype):
// xhr object def
var xhr = {
obj: function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
throw new Error("can't init xhr object");
},
get: function(url, fn) {
var xhr = this.obj();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
fn(xhr.responseText);
}
};
xhr.open("GET", url);
xhr.send(null);
}
};
// implementation
xhr.get("date.php", function(data){
xhr.get("doku.php?id=" + data.replace(" ", "_"), function(data){
alert(data);
});
});
It's not clear what you got wrong (can you tell us?), but I'd suggest to rely on some helper function like this:
function xhrGet(url, callback) {
if (window.XMLHttpRequest)
var xhr = new XMLHttpRequest();
else if (window.ActiveXObject)
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (!xhr) return;
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (typeof callback === "function") callback(xhr);
};
xhr.send(null);
return xhr;
}
So all you have to do is to use this function:
xhrGet("date.php", function(x1) {
xhrGet("doku.php?id=" + date.replace(" ", "_"), function(x2) {
// do stuff
// x1 and x2 are respectively the XHR object of the two requests
});
});
I'm curious as to why this isn't working, here's the code:
function Ajax(sUrl, fCallback) {
var url = sUrl || '';
var callback = fCallback || function () {};
var xmlhttp = (function () {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (err) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
} else {
return null;
}
}());
this.setUrl = function (newUrl) {
url = newUrl;
};
this.setCallback = function (func) {
callback = func;
};
this.request = function (method, data) {
if (xmlhttp === null) { return false; }
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
callback(xmlhttp.status, xmlhttp.responseXML, xmlhttp.responseText);
}
};
data = data || '';
data = encodeURIComponent(data);
if ((/post/i).test(method)) {
xmlhttp.open('POST', url);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
} else {
var uri = data === '' ? url : url + '?' + data;
xmlhttp.open('GET', uri);
xmlhttp.send();
}
return true;
};
return this;
}
var ajax = new Ajax(''); // sets the url, not necessary for this demonstration
var changed = false;
function change() {
changed = true;
}
function foo() {
ajax.setCallback(change);
ajax.request();
alert(changed);
}
foo();
There is a fiddle here: http://jsfiddle.net/dTqKG/
I feel like the change function would create a closure that would indeed change the changed variable. Does anyone know what's going on?
The ajax.request(); will return before change() is called. That is the async nature of the AJAX calls, and the reason why you need the callback as opposed to just getting return value from send() method.
Other than that there might be some other issues in the code. I question why wouldn't you use one of the many AJAX frameworks readily available instead of writing your own.
In the change_text() function I am trying to pass it the xmhttp.responsetext variable.. but how will I do this? As I see no way yet on how to pass it?
<script type="text/javascript">
function ajax(url, func) {
this.url = url;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 2 && xmlhttp.status == 200) {
this.func = func;
}
}
xmlhttp.open();
xmlhttp.send()
}
function change_text() {
target = document.getElementById("x");
target.innerHTML = xmlhttp.responseText;
}
ajax("url.php", change_text);
</script>
Actually, to do this you don't want to use this at all, since you are not creating any instances of an object and it doesn't act like a constructor.
You can just:
function ajax(url, func) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// note: loaded is 4 ^
func(xmlhttp.responseText);
}
}
xmlhttp.open('GET', url, true);
// ^~~ you also forgot to pass parameters here
xmlhttp.send('');
}
That would make the ajax function work.
For your change_text function, it's not in the same function as ajax, so it does not have access to the xmlhttp variable. However, the ajax function passed the responseText to it, so just make your function receive it:
function change_text(responseText) {
var target = document.getElementById("x");
// ^~~ don't forget to declare local variables with `var`.
target.innerHTML = responseText;
}
For a working example, see the jsFiddle.
Change this.func = func; to this.func = function () { func(xmlhttp.responseText); };
<script type="text/javascript">
function ajax(url, func) {
this.url = url;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 2 && xmlhttp.status == 200) {
func(xmlhttp);
}
}
xmlhttp.open();
xmlhttp.send()
}
function change_text(xmlhttp) {
target = document.getElementById("x");
target.innerHTML = xmlhttp.responseText;
}
ajax("url.php", change_text);
</script>
You have to call your callback with parameters. Also note that this.url = url just sets window.url = url which is probably a bug.
You probably want xmlhttp.open("POST", url) instead.
Mike Samuel is almost correct, but change_text is missing an argument, try this:
<script type="text/javascript">
function ajax(url, func) {
this.url = url;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//did you mean: func(xmlhttp.responseText);
if(xmlhttp.readyState == 2 && xmlhttp.status == 200) {
this.func = function() {
func(xmlhttp.responseText);
};
}
}
xmlhttp.open();
xmlhttp.send()
}
function change_text(responseText) {
target = document.getElementById("x");
target.innerHTML = responseText;
}
ajax("url.php", change_text);
</script>