Getting response from server in javascript - 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);
}
}
}
}

Related

How to clear session whenever close the browser?

var clicked = false;
function CheckBrowser() {
// debugger;
if (clicked == false) {
//Browser closed
} else {
//redirected
clicked = false;
}
}
function bodyUnload() {
if (clicked == false)//browser is closed
{
var request = GetRequest();
// request.open("GET", "../../LogOut.aspx", true);
request.open("GET", "LogOut.aspx", true);
request.send();
}
}
function GetRequest() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
this is my javascript code.
I want to clear session when browser closed but its not working?
I am sending request to this on logout.aspx but it doesn't work.

ie8: unknown runtime error

i have this problem only in ie8
here is my javascript code
var bustcacheparameter="" ;
function createRequestObject(){
try {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
};
return xmlhttp;
};
function ajaxpage(url, containerid){
var page_request = createRequestObject();
if (bustcachevar) bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
document.getElementById(containerid).innerHTML=page_request.responseText;
};
}
function LoadMonth(month, year) {
ajaxpage("calendar.php?month="+month+"&year="+year, "Calendar")
}
LoadMonth();
i use ie tester to know this error
line : 26
char : 6
unknown runtime error
TRY this ; its for compatability issues i.e
i hope it helps
AJAX support
function createXMLHttpRequest()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
function getModIndex(val) {
var divEle = "IndexDiv" + val;
var request = createXMLHttpRequest();
if ( !request ) {
alert( request )
return false
}
var callback = function( oXML ) {
document.getElementById( divEle ).innerHTML = oXML.responseText;
}
request.connect(
'../ajax/ajax-GetIndex.php',
'POST',
'id=' + val,
callback
);
}

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

Ajax Not Working Right In Chrome/FireFox

This script I wrote works perfect on IE! It works on Chrome and FireFox the first time you do an action but it fails on the rest.
The script is simple. You can Add or Delete a user and each time you Add or Delete a user it updates the Updates the list.
function Add() {
http_request = false;
cache=Math.random();
var username=document.getElementById('username').value;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
return false;
}
http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ if (http_request.responseText=="OK"){ Update(); } else { document.getElementById('Response').innerHTML=http_request.responseText; } } }
http_request.open('POST', 'add.php?username='+username+'&cache='+cache, true);
http_request.send(null);
}
function Delete(username) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
return false;
}
http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ Update(); } }
http_request.open('POST', 'delete.php?username='+username, true);
http_request.send(null);
}
function Update() {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
return false;
}
http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ document.getElementById("list").innerHTML=http_request.responseText; } }
http_request.open('GET', 'list.php', true);
http_request.send(null);
}
Please help and thank you
Use jQuery. You will have to write much less code and it will work in all browsers.

AJAX issue, works in all browsers except IE

This code works in Chrome and Firefox, but not IE (which is to be expected). Does anyone see anything wrong with this code that would render it useless in IE?
var waittime=400;
chatmsg = document.getElementById("chatmsg");
room = document.getElementById("roomid").value;
sessid = document.getElementById("sessid").value;
chatmsg.focus()
document.getElementById("chatwindow").innerHTML = "loading...";
document.getElementById("userwindow").innerHTML = "Loading User List...";
var xmlhttp = false;
var xmlhttp2 = false;
var xmlhttp3 = false;
function ajax_read() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("chatwindow").innerHTML = xmlhttp.responseText;
setTimeout("ajax_read()", waittime);
}
}
xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true);
xmlhttp.send(null);
}
function user_read() {
if(window.XMLHttpRequest){
xmlhttp3=new XMLHttpRequest();
if(xmlhttp3.overrideMimeType){
xmlhttp3.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp3) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState==4) {
document.getElementById("userwindow").innerHTML = xmlhttp3.responseText;
setTimeout("user_read()", 10000);
}
}
xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true);
xmlhttp3.send(null);
}
function ajax_write(url){
if(window.XMLHttpRequest){
xmlhttp2=new XMLHttpRequest();
if(xmlhttp2.overrideMimeType){
xmlhttp2.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp2) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp2.open('GET',url,true);
xmlhttp2.send(null);
}
function submit_msg(){
nick = document.getElementById("chatnick").value;
msg = document.getElementById("chatmsg").value;
document.getElementById("chatmsg").value = "";
ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + "");
}
function keyup(arg1) {
if (arg1 == 13) submit_msg();
}
var intUpdate = setTimeout("ajax_read()", waittime);
var intUpdate = setTimeout("user_read()", 0);
I'm going to avoid the question slightly and suggest you use jQuery =P. 90% of your code would evaporate. For example, your user_read function would become:
function user_read() {
$.ajax({
type: "GET",
url: "methods.php",
data: {method: "u", room: room}
dataType: "html"
success: function (data, status, xhr) {
$("#userwindow").html(data);
setTimeout(user_read, 10000);
}
});
}
Furthermore, jQuery is also designed to work on all browsers, so you shouldn't have IE problems any more.
Try run on IE some example using jQuery library - just for partial test that browser is 'ok' and code have bug.
jQuery would be best for multiple ajax requests. Else, there are quite a few problems that more advanced browsers automatically fix, while IE may fail on. A few missing semicolons.
You also have 2 intUpdate declarations for 2 different intervals at the end. I've also noticed that "xmlhttp2" has no onreadystatechange function.
Using a checker like JSLint will help alot.
I did my best with your code. Try this, it should result in no errors:
var waittime = 400;
chatmsg = document.getElementById("chatmsg");
room = document.getElementById("roomid").value;
sessid = document.getElementById("sessid").value;
chatmsg.focus();
document.getElementById("chatwindow").innerHTML = "loading...";
document.getElementById("userwindow").innerHTML = "Loading User List...";
var xmlhttp = false;
var xmlhttp2 = false;
var xmlhttp3 = false;
function ajax_read() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("chatwindow").innerHTML = xmlhttp.responseText;
setTimeout(function(){ajax_read();}, waittime);
}
};
xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true);
xmlhttp.send();
}
function user_read() {
if(window.XMLHttpRequest){
xmlhttp3=new XMLHttpRequest();
if(xmlhttp3.overrideMimeType){
xmlhttp3.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState==4) {
document.getElementById("userwindow").innerHTML = xmlhttp3.responseText;
setTimeout(function(){user_read();}, 10000);
}
};
xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true);
xmlhttp3.send();
}
function ajax_write(url){
if(window.XMLHttpRequest){
xmlhttp2=new XMLHttpRequest();
if(xmlhttp2.overrideMimeType){
xmlhttp2.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp2.open('GET',url,true);
xmlhttp2.send();
}
function submit_msg(){
nick = document.getElementById("chatnick").value;
msg = document.getElementById("chatmsg").value;
document.getElementById("chatmsg").value = "";
ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + "");
}
function keyup(arg1) {
if (arg1 == 13) {submit_msg();}
}
var intUpdate = setTimeout(function(){ajax_read();}, waittime);
user_read();

Categories