variable value from http request / javascript - javascript

I am doing a http request in js but I cannot access the data I get from outside.
if (window.XMLHttpRequest)
{
search=new XMLHttpRequest();
}
else
{
search=new ActiveXObject("Microsoft.XMLHTTP");
}
search.onreadystatechange=function()
{
if (search.readyState==4 && search.status==200)
{
nr = search.responseText;
alert(nr.length); // here i get the actual length
}
}
search.open("GET","clienti.php",true);
search.send();
alert(nr); // here the value is undefined
I tried to declare variable globally but still doesnt work. Please help!
Thanks!

var nr;
if (window.XMLHttpRequest)
{
search=new XMLHttpRequest();
}
else
{
search=new ActiveXObject("Microsoft.XMLHTTP");
}
search.onreadystatechange=function()
{
if (search.readyState==4 && search.status==200)
{
nr = search.responseText;
alert(nr.length); // here i get the actual length
}
}
search.open("GET","clienti.php",true);
search.send();
alert(nr);
With your code nr is private to onreadystatechange block.

you have scope problem define nr as global variable and than try
var nr=0;
if (window.XMLHttpRequest)
{
search=new XMLHttpRequest();
}
else
{
search=new ActiveXObject("Microsoft.XMLHTTP");
}
search.onreadystatechange=function()
{
if (search.readyState==4 && search.status==200)
{
nr = search.responseText;
alert(nr.length); // here i get the actual length
}
}
search.open("GET","clienti.php",true);
search.send();
alert(nr); /

Related

javascript poll php script every 5 seconds

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);

XMLHttpRequest status is 0 why?

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);
}
}

How to make javascript wait until it gets a valid response from synchronous http request?

I know it is not a good idea to use synchronous requests but this is the case that I really need it.
I have tried to make getEndDate function calling to itself if response lenght is less than 20 but after the first unsuccessfull request (if url gives too short response) it goes to alert(enddate.EDDAYOW); and I am getting error, and getEndDate continues sending request every 500 ms.
I need getEndDate function to continue sending a request until it get a valid response and return valid object, and only after that continue to the next line of JS. How to achieve that?
var url = 'http://local.com/cgi-bin/hello2.pl';
// url returns a plain text:
// 1234567890 2013 05 May Friday 13 23 45 01
var enddate = getEndDate(url);
alert(enddate.EDDAYOW);
function getEndDate(url) {
var xmlhttp = getXmlHttp();
xmlhttp.open('GET', url, false);
xmlhttp.send();
if (xmlhttp.status == 200 && xmlhttp.responseText.length > 20) {
var n = xmlhttp.responseText.split(" ");
return {
'edseconds': n[0],
'EDYEAR': n[1],
'EDMON': n[2],
'EDMONNAME': n[3],
'EDDAYOW': n[4],
'EDDAY': n[5],
'EDHOUR': n[6],
'EDMIN': n[7],
'EDSEC': n[8]
};
} else {
setTimeout("getEndDate(" + url + ")", 500);
}
}
function getXmlHttp() {
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;
}
I don't know if this satisfies your requirement, but I would rewrite it to something like this:
var enddate;
getEndDate(url);
function do_rest(returnDate)
{
enddate = returnDate;
alert(enddate.EDDAYOW);
// do more if you need
};
function getEndDate(url) {
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200 && xmlhttp.responseText.length > 20) {
var n = xmlhttp.responseText.split(" ");
do_rest({
'edseconds': n[0],
'EDYEAR': n[1],
'EDMON': n[2],
'EDMONNAME': n[3],
'EDDAYOW': n[4],
'EDDAY': n[5],
'EDHOUR': n[6],
'EDMIN': n[7],
'EDSEC': n[8]
});
} else {
setTimeout("getEndDate(" + url + ")", 500);
}
}
}
xmlhttp.open('GET', url, false);
xmlhttp.send();
}

Run one ajax after another one

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
});
});

Getting response from server in javascript

How does I get the response from the server in JavaScript? This is my sample code:
function get_Image(values) {
if (window.XMLHttpRequest) {
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http_request.open("GET", "http://sample_address_for_server", true);
http_request.send();
}
alert(http_request.status);
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}
}
}
Try using this block .. the problem with your code is that you missed the quote while creating the open connetion
function get_Image(values){
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("MSXML2.XMLHTTP")
} catch () {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch () {}
}
} else {
return false
}
}
http_request.onreadystatechange = function () {
alert(http_request.status);
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}}
};
http_request.open( "GET", "http://sample_address_for_server", true);
http_request.send(null);
}
you have to attach a function to the object's onreadystatechange event. The way you are doing, you are trying to get the response imediately after you sent the request, you don't have any response yet.
function get_Image(values) {
if (window.XMLHttpRequest) {
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http_request.open("GET", "http://sample_address_for_server", true);
http_request.send();
}
alert(http_request.status);
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}
}
}
}

Categories