I tried to use global variable and use return clause, but the variable remains null when left the AJAX function.
http.onreadystatechange =
function() { if(http.readyState==4 && http.status==200) {
vQuantity = http.responseText;
alert(vQuantity);
}
}
The alert message (above) showed me a valid value and the variable is global, but returning of the AJAX function the value is null. Do you all have any ideas?
Thanks buddies, Marcos.
The AJAX routine was ok, but I'd like to use a variable that was loaded (at least should to be) outside AJAX routine and the variable is null.
How can I do this? Below you all can see my code:
<form><input type=hidden name="ElementoQuantidade"></form>
function updateinsertAJAX(CodPagina) {
var http;
if (window.XMLHttpRequest) {
http=new XMLHttpRequest();
}
else
{
http=new ActiveXObject("Microsoft.XMLHTTP");
}
var urlalvo = "updateinsertSQL.php";
var compl = "?codpagina=" + CodPagina + "&t=";
var randomize = parseInt(Math.random()*999999999999999);
var modurl = urlalvo + compl + randomize;
http.open("GET", modurl, true);
http.onreadystatechange =
function() { if(http.readyState==4 && http.status==200) {
var vqtde = http.responseText;
document.getElementById('ElementoQuantidade').innerHTML = vqtde;
}
else
{
document.getElementById('ElementoQuantidade').innerHTML = "a lot of";
}
}
http.send();
}
Actually, I'd like to use that variable vqtde, but when I use it outside AJAX function, that variable (vqtde) is null. Inside AJAX function the variable (vqtde) has a valid value.
Could you please guide me? Thanks a lot and have a pleasant day.
Marcos
var vqtde; // make it global
function updateinsertAJAX(CodPagina) {
var http;
if (window.XMLHttpRequest) { ........
AND
http.onreadystatechange =
function() { if(http.readyState==4 && http.status==200) {
vqtde = http.responseText; ....
Why don't you return the value from your function? I would advise against global variables unless they're necessary, just because they can get lost in the shuffle if your application grows.
function yourFn(...) {
...do some stuff...
return yourVariable;
}
Related
My code is running inside a main function. One part of my code is to make an HTTP request with an parameter which was defined before in the function and than write the response in to a new variable and work with it later.
I would like to exclude these steps with HTTP Request outside of the main function, and just CALL the function and write the response in a variable.
Unfortunately I tried it, but it doesn't work.
Error: variable is undefined
My code:
function DoWork() {
//some code
var strResponseHttpRequest;
strResponseHttpRequest = HttpRequest(strInput, function(strInput) {
console.log(strInput);
};
//continue working with the variable 'strResponseHttpRequest'
//rest of my code
}
function HttpRequest(strInput, callBackMethod) {
var objRequest = new XMLHttpRequest(); //New request object
objRequest.onreadystatechange = function() {
// Waits for correct readyState && status
if (objRequest.readyState == 4 && objRequest.status == 200) callBackMethod(objRequest.responseText)
}
objRequest.open("get", "php/get-content.php?ID=" + strInput, true);
objRequest.send();
}
I hope you can help me to find out, where the issue is. If there are some better way to do this, let me know. I would be appreciate it. Thank you.
Do you mean an asynchronous callback? You'll want to wait until the server gives back the correct status and readyState.
Change this:
objRequest.onload = function() {
var strResponse = this.responseText;
return strResponse;
};
To this:
objRequest.onreadystatechange = function() {
// Waits for correct readyState && status
if (objRequest.readyState == 4 && objRequest.status == 200) callBackMethod(objRequest.responseText);
};`
and pass in a callback method as a second parameter to HttpRequest(strInput, callbackMethod) like so:
strResponseHttpRequest = HttpRequest(strInput, function(responseText) {
console.log(responseText);
});
Also add callbackMethod as a parameter like so:
HttpRequest(strInput, callbackMethod)
Where is your strInput variable in your DoWork() function coming from? Maybe you forgot to define it somewhere? Could be for example:
function DoWork(strInput) {
//some code
var strResponseHttpRequest;
strResponseHttpRequest = HttpRequest(strInput);
console.log(strResponseHttpRequest);
//continue working with the variable 'strResponseHttpRequest'
//rest of my code
}
function HttpRequest(strInput) {
function reqListener () {
console.log(this.responseText);
}
var objRequest = new XMLHttpRequest(); //New request object
objRequest.onload = function() {
var strResponse = this.responseText;
return strResponse;
};
objRequest.open("get", "php/get-content.php?ID=" + strInput, true);
objRequest.send();
}
DoWork("yourIDvalue");
to resume my problem, i'm using many XMLHttpRequest() rockets, with a view to get the value (miniTable) returned by the TableRow() function. The problem is, with the alert() on the end of the TableRow() function, i'm have exactly the value that i want, but on TableContent2 variable i'm having an "Undefined" value. I don't know why!! here all the JS file that i'am using (don't care about variables and code calculating the variables). I really need your help, because i'm blocked since 3 days on that. Thank you again and good afternoon freinds.
(function() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "File1.xml", true);
xmlhttp.send();
})();
function ContentFunction(func) {
TableContent2 = TableRow();
alert(TableContent2);
}
function TableRow() {
xmlhttp3 = new XMLHttpRequest();
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState == 4 && xmlhttp3.status == 200) {
texttest = myFunction2(xmlhttp3);
alert(miniTable);
return miniTable;
}
};
xmlhttp3.open("GET", "File2.xml", true);
xmlhttp3.send();
}
function myFunction2(xml) {
var xmlDoc2 = xml.responseXML;
var ObjectText;
var x = xmlDoc2.getElementsByTagName("Clip");
/*Calcule de ObjectText*/
alert(ObjectText);
return ObjectText;
}
function myFunction(xml) {
xmlhttp2 = new XMLHttpRequest();
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Film");
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
myFunction2(xmlhttp2);
}
};
xmlhttp2.open("GET", "File2.xml", true);
xmlhttp2.send();
}
TableRow returns nothing. The return statement at xmlhttp3.onreadystatechange isn't in the earlier scope. Besides that, your xmlhttp3 is set to be asynchronous, then you can't directly return any information of the AJAX. Synchronous requests, which are deprecated (that's why you shouldn't use them), can be directly read, since they act like a infinite loop that breaks when the request is done (for(;xhr.readyState!==4;);, doing this manually will pause the request and the script execution forever, this is why synchronous requests have been made before.).
Synchronous requests aren't a good idea, they break interaction with entire of the page, since they pause the page/script execution. For instance, if you've a animation, it'll be paused, including event listeners.
Also, it looks like miniTable haven't been declared in any part of your code.
Consider using callback functions, they'll be stored in the TableRow scope and can be called later, with extra arguments.
This is a base:
function ContentFunction(func) {
TableRow(function(TableContent2) {
alert(TableContent2);
});
}
function TableRow(doneFnc) {
var xmlhttp3 = new XMLHttpRequest;
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState === 4 && xmlhttp3.status === 200) {
var texttest = myFunction2(xmlhttp3);
/* success callback */
doneFnc(texttest);
}
};
xmlhttp3.open("GET", "File2.xml", true);
xmlhttp3.send();
}
I am trying to read a local file on the server with a standard function loadDoc(url, cfunc), then
1) search for a particular string in the file (getLine());
2) if possible, store that line to a variable.
For point 1 I pass a string to the callback.
2) Getting the response is problematic because XMLHTTPRequest is asynchronous. At this moment the error is:
"ReferenceError: xhttp is not defined"
function main(){
var url="data.txt"
var str="1,0,"; //just an example
var myCallBackWithVar = function(){
getLine(str);
};
loadDoc(url, myCallBackWithVar);
//Can I get the line here somehow?
}
function loadDoc(url, cfunc) {
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
}
xhttp.overrideMimeType('text/plain');
xhttp.open("GET", url, true);
xhttp.send();
}
//Find string with the desired data in txt file
function getLine(str) {
var data=xhttp.responseText;
//Find the line from the txt file
var start=data.indexOf(str);
var end=data.indexOf(";",start);
var line=data.substring(start,end);
return line;
}
data.txt is something like this:
some data here
0,0,9;
1,0,10;
1,1,11;
I have already tried to pass the XMLHTTPRequest objetct getLine(xhttp,str). How to solve points 1 and 2? I'd rather keep it jQuery free for the moment. Thanks
Can I get the line here somehow?
I don't think that's a good idea. You can't be sure that your app will work correctly. XHR is a async function and you should use async architecture.
Here the example how this functionality can be done.
var text; // define global variable
var str = "1,0,"; //just an example
function main(){
var url = "data.txt";
var cb = function (data){
text = getLine(data);
// you can use text var here
// or in anyewhere in your code
}
loadDoc(url, cb);
}
function loadDoc(url, cb) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
cb(xhr.responseText);
}
}
xhr.overrideMimeType('text/plain');
xhr.open("GET", url, true);
xhr.send();
}
//Find string with the desired data in txt file
function getLine(data) {
if(data) {
//Find the line from the txt file
var start = data.indexOf(str);
var end = data.indexOf(";", start);
var line = data.substring(start, end);
return line;
}
}
On complete, you don't need to pass the whole xhttp variable through too the callback function. When you do this:
function getLine(str) {
var data=xhttp.responseText;
xhttp is already out of scope. To fix this, the parameter name would also have to be xhttp.
A better way would be to do :
cfunc(xhttp.responseText);
and then
var data=str
This way, you are passing only what you need as an argument.
I have a function which attempts to capture a return value from a calling function in the following manner:
var select = xhrRetrieve(projID);
Here is an example of the xhrRetrieve function:
function xhrRetrieve(projID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var obj = $.parseJSON(xhr.responseText);
return obj.select.toString();
}
}
}
var url = "ajax.cgi";
var data = "action=retrieve-opp&proj-id=" + projID;
xhr.open("POST",url);
xhr.setRequestHeader("Content-Type","application/x-www-urlencoded");
xhr.send(data);
}
I am using jQuery in conjunction with straight JavaScript. Whenever I attempt to get the value of obj.select using:
var select = xhrRetrieve(projID);
Select always comes back undefined.
What am I doing wrong?
The function doesn't return anything
The moment you call your function, the (not currently present) return value is being assigned to select. At the same moment, your ajax request is being fired, which takes time to complete; the callback function will not be called until the ajax request has completed (and succeeded).
This should work:
function doStuffWithTheAjaxResponse(select) {
// do stuff
}
function xhrRetrieve(projID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var obj = $.parseJSON(xhr.responseText);
doStuffWithTheAjaxResponse(obj.select.toString());
}
}
}
var url = "ajax.cgi";
var data = "action=retrieve-opp&proj-id=" + projID;
xhr.open("POST",url);
xhr.setRequestHeader("Content-Type","application/x-www-urlencoded");
xhr.send(data);
}
Since the request is asynchronous the function will return before your code in onreadestatechange fires. You can switch to synchronous and get the value before the function returns:
function xhrRetrieve(projID) {
var returnVal;
var xhr = new XMLHttpRequest();
var url = "ajax.cgi";
var data = "action=retrieve-opp&proj-id=" + projID;
//3rd param is false to switch to synchronous
xhr.open("POST",url, false);
xhr.setRequestHeader("Content-Type","application/x-www-urlencoded");
xhr.send(data);
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var obj = $.parseJSON(xhr.responseText);
return obj.select.toString();
}
}
}
The function xhrRetrieve doesn't have a return value. What do you expect to happen?
You have two functions there. The inner function returns a value, but not the outer one. The inner function is an event handler so the return value doesn't go anywhere. Your XMLHttpRequest is asynchronous, so you won't get a return value right away. See this post for a more detailed explanation: parameter "true" in xmlHttpRequest .open() method
To call, for example, a function named makeRequest, I learned you need to do makeRequest();. If you only do makeRequest; it is a reference to the function (I thought). Yet, looking at this code (which worked when I tested it), it calls makeRequest; on the window.onload without the parens.
Can someone explain?
window.onload = makeRequest;
var xhr = false;
function makeRequest() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", "colors.xml", true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}
On this line:
window.onload = makeRequest;
the function makeRequest is not called. You only assign the function pointer to the onload event. When the DOM is loaded the browser automatically calls this event and it it is only at that moment that the function it is pointing to is invoked (which might happen much later but leave you with the impression that the function is called immediately).
It's a reference when used on the right-side of an expression. ie
var x = myfunction;
would set x to be a "pointer" to myfunction.
var x = myfunction();
would store the value returned-by-myfunction into x.