Variable out of scope [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?
After whole day without solution to this. I read that this isn't possible or cant be done etc. I did go trough all of topics related, but cant find solution.
So i think my variable in code is out of scope and i cant return it, cant use it.
js file:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send();
}
So here above is ok, its returning value of php script when its finished.
And i want this myvar variable in html file. Tried like this:
window.onload = function() {
var myvar = MakeRequest();
alert (myvar);
}
It fails, returning undefined value.
Tried also making MakeRequest function as callback function, and then calling it from html like
MakeRequest(function(txt){
});
Then I got response, but can just alert it. I don't want to alert it. I need it to be stored in variable myvar because its needed later in code.

Related

Getting variable from ajax function

I've this function.
function ajaxtakesource4(callback){
var ajaxRequest; // The variable that makes Ajax possible!
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange =function(){
if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
var sourcetest = ajaxRequest.responseText;
callback(sourcetest);
}
}
ajaxRequest.open("POST", "takesource4.php", true);
ajaxRequest.send(null);
}
Also:
var somous4;
function run() {
ajaxtakesource4(function(sourcetest){
somous4=sourcetest;
});
alert(somous4);
}
and here I call the above the function:
<div id="run">
<button id="button_run" class="button" onclick="run()">Run</button>
</div>
To make it clear i need to use the variable of somous4 in the function run not only to print it. My idea is to call a number of variables , with the same procedure. I need to store,use these variable by the some way(this is what i am searching) use all of them in the function and run the algorithm. I need something like to return these variables (i think it is not possible) or to use them as global variables in the function run. Thanks for your interest!

XHR object creation

What difference between:
var xmlhttp = getXmlHttp()
and
var xmlhttp = new XMLHttpRequest()
?
If I correctly understand, each of this two cases create XRH object.
Please look at this function:
function getXMLHttp() {
var x = false;
try {
x = new XMLHttpRequest();
}
catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
getXMLHttp() is your custom function to simplify the creation an XHR object with the cross browser issues.
XMLHttpRequest is an object to used with the current modern browser. For the old browser like IE5 or IE6, you can use ActiveXObject("Microsoft.XMLHTTP");
However, the return object is the same for each browser.
If you open up Chrome Developer tools and try the following:
> getXmlHttp()
ReferenceError: getXmlHttp is not defined
This indicates that getXmlHttp is not a built in function.

AJAX Uncaught reference error

Script.js:
var request = new XMLHttprequest();
request.open('GET','data.txt',false);
if(request.status===200) {
console.log(request);
document.writeln(request.responseText);
}
This is my javascript file. I am getting this error:
Uncaught reference error:XMLHttprequest is not defined
Please help.
Sincere thanks.
I tried this it's simple mistake,
var request = new XMLHttpRequest();
dont use the simple letter for xmlHttpRequest. It should be a XMLHttpRequest. Also your simple r should be a capital R. it's work for me.Also try a different version of browser.
This line:
var request = new XMLHttprequest();
Should be:
var request = new XMLHttpRequest();
//^ Capital 'R'
Case in JavaScript, like most languages, matters
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");//this is for ie
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//this is for ie
} catch (E) {
try{
xmlhttp =new XMLHttpRequest();//for browsers other than ie
}
catch(e)
{
}
}
For browsers like ie XMLHttpRequest doesnt work
Try the following method to get your XML HTTP Request:
function GetXmlHttpObject()
{
try {
var xmlHttp = null;
if (window.XMLHttpRequest)
{
// If IE7, Mozilla, Safari, etc: Use native object
xmlHttp = new XMLHttpRequest()
}
else
{
if (window.ActiveXObject)
{
// ...otherwise, use the ActiveX control for IE5.x and IE6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
} catch(e)
{
alert(e.message);
}
}

AJAX div not updating without alert call with error: b.data is undefined

First of all, any suggestions on rewriting my title?
Issue:
I have an AJAX updatable div, when my error checking alert calls are in, everything works perfect. But when I remove a specific one, the DIV never gets updated. I know it sounds confusing, but code is as follows, and then I will explain further.
AJAX SCRIPT
var xmlhttp
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp=false
}
}
#else
xmlhttp=false
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false
}
}
function myXMLHttpRequest() {
var xmlhttplocal;
try {
xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttplocal=false;
}
}
if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
try {
var xmlhttplocal = new XMLHttpRequest();
} catch (e) {
var xmlhttplocal=false;
alert('couldn\'t create xmlhttp object');
}
}
return(xmlhttplocal);
}
function sndReq(page,key,includesDir,changeDiv,parameterString) {
var divToChange = document.getElementById(changeDiv); // the Div that the data will be put into
// Place loading image in container DIV
divToChange.innerHTML = '<div class="loading">Loading</div>';
if (includesDir == 1){
//Find Current Working Directory. Use to find path to call other files from
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var arraytext = locarray.join("/");
xmlhttp.open("POST","AJAXCaller.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(parameterString);
} else {
}
xmlhttp.onreadystatechange = handleResponse(changeDiv);
xmlhttp.send(null);
}
function handleResponse(changeDiv) {
/* ======== If I remove the following line script halts ================*/
/* ======== If line stays here, script executes perfectly ==============*/
alert('to changetext 1\n'+xmlhttp.responseText);
/* =========End of line removal issue =================================*/
if(xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
var response = xmlhttp.responseText;
var update = new Array();
if(response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
} else {
changeText(changeDiv, response);
}
} //End IF xmlhttp.status == 200
}
}
function changeText( div2show, text ) {
// Detect Browser
var IE = (document.all) ? 1 : 0;
var DOM = 0;
if (parseInt(navigator.appVersion) >=5) {DOM=1};
// Grab the content from the requested "div" and show it in the "container"
if (DOM) {
var viewer = document.getElementById(div2show);
viewer.innerHTML = text;
} else if(IE) {
document.all[div2show].innerHTML = text;
}
}
When I check my Firefox error console, this error ONLY appears when I remove that alert as defined in the code:
Timestamp: 5/30/2012 5:07:55 PM
Error: b.data is undefined
Source File: http://cdn.sstatic.net/js/wmd.js?v=cfd2b283af83
Line: 92
I am an advanced PHP/mySQL developer, but have been trying hard to grasp AJAX/JavaScript. Doing tutorials like mad. So please be descriptive in comments/answers so I can use them as a reference for learning...
Why would displaying an alert box alter code execution (for the better!) in any way?
NEW ERRORS - Google Chrome and Firefox Console (sigh...)
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
sndReqAJAX.js:89
element.onclick
Line 89 is the following (verified by Google Chrome Console)
xmlhttp.send(null);
Everything I find on the web refers to extremely complex issue regarding DOM objects not existing... This wouldn't apply here, would it?
First, the problem. This is the line:
xmlhttp.onreadystatechange = handleResponse(changeDiv);
The reason this is wrong is that xmlhttp.onreadystatechange should be a function - you need to assign a function to the property, what you are doing is calling the function and assigning the return value to the property. This is not in itself a problem, as long as your function returns a function. Which it doesn't.
If you're used to working with PHP (especially if your used to working with PHP <5.3) you may not be used to this concept. Javascript has support for closures in a way that anyone who doesn't use them much will find confusing.
What the line needs to look like is this:
xmlhttp.onreadystatechange = handleResponse;
By appending (changeDiv) you are calling the function, whereas what you need to do is simply pass it, like you would any other value.
Now, where it gets complicated is that you want to pass an argument that is local to the scope of the calling function. There are a number of ways to handle this, but a cursory look at your code tells me that handleResponse() is not used anywhere else, so it would be better to define this as a closure and not litter the global scope with a named event handler. This also overcomes the variable scoping problem:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var response = xmlhttp.responseText;
var update = []; // "new Array()" is baaaad
if (response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
} else {
changeText(changeDiv, response);
}
} //End IF xmlhttp.status == 200
}
};
Replace the aforementioned offending line with that block of code, and remove the handleResponse() function definition, and that should solve the immediate problem. Now, as to why the alert() "fixes" your original code - this is a little hard to explain, but I shall have a go... give me a minute to inspect the code properly
Attempt at a full and comprehensible explanation abandoned. If anyone wants one, post a comment and I'll have another go at it when I've had some sleep...

Ajax response works after two clicks?

I just wrote a basic user-login system where the html page uses javascript to send the ajax request to a servlet which accesses through database.
Here's the js code
var res;
function getXMLObject()
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
res=xmlhttp.responseText;
}
else {
return false;
alert("Error during AJAX call. Please try again");
}
}
function ajaxFunction() {
var veid=document.getElementById("eid").value;
var vpwd=document.getElementById("pwd").value;
//window.alert('here inside ajaxFunction'+vconf+' '+vseid);
if(xmlhttp) {
xmlhttp.open("GET","check_login?eid="+ veid +"&pwd="+ vpwd,true); //this is the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function def()
{
//window.alert('hi');
ajaxFunction();
//alert('res:'+res);
if(res=='y')
{
return true;
}
else
{
document.getElementById("uhidden").style.color="#CC0000";
document.getElementById("uhidden").innerHTML="Invalid E-Mail ID or Password"
return false;
}
}
But the code works only after two clicks :(
Any help guys?
Your def function calls ajaxFunction and then straight away checks the res variable. However ajaxFunction just sends the AJAX request; it does not wait for the AJAX response to arrive. Your code is checking the res variable before it is being set from the AJAX response.
This is why it works on the second click - not because the res variable is being set by the second click's AJAX response, but because it is still set from the first click's AJAX response.
The solution is to re-arrange your code a bit. Move the code to display the invalid login message to where the AJAX response is received. In other words, replace the res=xmlhttp.responseText; line with some code to check if xmlhttp.responseText is not y and display the invalid login message.
I guess you call def()
Your Request ist asynchron(because you set the 3rd argument of open() to true ), but in def() you immediately after sending the request work with the the result:
ajaxFunction();
//alert('res:'+res);
if(res=='y')
At this time the request usually is not finished, the result not available yet
Put all code that has to work with the server-response into handleServerResponse()

Categories

Resources