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);
}
}
Related
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));
It will always display the "cretetion" associated link JSON as the others are overwritten. So I tried incrementing to get all of them, but it didn't work. I don't know what I am doing wrong.
var users = ["ESL_SC2", "OgamingSC2", "cretetion"];
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
for (var i = 0; i < users.length ; i++) {
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + users[i];
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById('online-id').innerHTML += (xmlhttp.responseText + "<br />");
}else if (xmlhttp.status == 400) {
console.log('There was an error 400');
}else {
console.log('Something else other than 200 was returned.');
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
var onlineButton = document.getElementById('online-button-id');
onlineButton.addEventListener('click', loadXMLDoc, false);
I've fixed your code here:
https://plnkr.co/edit/VbkKc9QuVALAYLpujSdo?p=preview
First, the callback xmlhttp.onreadystatechange is overwritten every iteration of the loop so only the last element will be handled.
you should create and manage the XMLHttp object inside the loop, one for each element of your user array.
Secondy and most important you must wrap xmlhttp.onreadystatechange inside an Immediate invoked function otherwise each callback will use the last xmlhttp object then you will be getting the last result all the time, as you were saying above.
for (var i = 0; i < users.length ; i++) {
var xmlhttp = new XMLHttpRequest();
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + users[i];
(function(xmlhttp){
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById('online-id').innerHTML += (xmlhttp.responseText + "<br/><br/>");
}else if (xmlhttp.status == 400) {
console.log('There was an error 400');
}else {
console.log('Something else other than 200 was returned.');
}
}
}
})(xmlhttp)
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Try creating a new XMLHttpRequest for each iteration of the loop instead of re-using the same one. i.e.
function loadXMLDoc() {
for (var i = 0; i < users.length ; i++) {
var xmlhttp = new XMLHttpRequest();
...
I'm trying to create an AJAX call with the post method, and can't get it to work right. The script hangs at the processing stage (readyState does not go on to 4).
I'd appreciate it if someone could enlighten me on the issue here. I've looked at a couple of tutorials, and it seems that my code -should- work.
function newRequestPost(url, post, threadid, cfunc) {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "post="+post+"&threadid="+threadid;
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params);
}
function openModalPreview(threadid) {
var post = document.getElementById("post_txt").value;
newRequestPost("url", post, threadid, function() {
if(xmlhttp.readyState == 1) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Loading...";
}
if(xmlhttp.readyState == 2) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Received";
}
if(xmlhttp.readyState == 3) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Processing...";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = xmlhttp.responseText;
}
});
}
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");
}
}
How do I check a value in a php script for change using javascript?
I would like to do something like:
<script type="text/javascript"><!--
var innitialID = get_file_contents(lastPresentID.php); //get_file_contents(lastPresentID.php);
function myTimeout() {
var freshestID = get_file_contents(lastPresentID.php);
if(freshestID != innitialID) {
location.reload();
}
setTimeout(myTimeout, 5000);
}
window.onload = myTimeout;
</script>
the php script generates a single integer which is the last ID of a table.
Thanks!
<script type="text/javascript">
window.onload = doAjax(true);
setInterval(doAjax, 5000);
var initialID = -1, freshestID;
function doAjax(initial) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
if(initial) {
initialID = xmlhttp.responseText;
} else {
freshestID = xmlhttp.responseText;
if (initialID != freshestID)
location.reload();
}
}
}
xmlhttp.open("GET", "lastPresentID.php", true);
xmlhttp.send();
}
</script>
Here we go, updated with ajax calls in there. First sets the initialId variable, then the interval code runs every 5 seconds and update the freshestId variable, and does the comparision.
EDIT: Code is now not duplicated.
The code below on load will assigns oldVal. Then using setInterval will update newVal every 5 secodns and check if newVal != oldVal.
It gets the values from lastPresentID.php using AJAX.
var oldVal = 0;
var newVal = 0;
function loadXMLDoc(old) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
if(old)
{
oldVal = xmlhttp.responseText;
}
else
{
newVal = xmlhttp.responseText;
if(newVal != oldVal)
alert("test");
}
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert(xmlhttp.status)
}
}
}
xmlhttp.open("GET", "lastPresentID.php", true);
xmlhttp.send();
}
function timeout() {
loadXMLDoc(false);
}
loadXMLDoc(true);
setInterval(timeout, 5000);