Function Not Returning Value To Other Function
Solution 1:
In your code you are using AJAX trough JQuery:
$.get(url, callback)
The $get
method hits the url
and passes the result to the callback method, it does not return it. The callback
does not get invoked immediately, due to AJAX being asynchronous, instead something like this happens:
$.get
is called- the
read
method continues (exits in your case, as there is no other code) - the
$.get
receives a response from the server - the
callback
function gets called, if the server succeeded with getting the data
In the above sequence, the second step may be swapped with any of the steps after it. Still, this sequence is to show that there is no relationship between when the read
method exits and when the processing of the data occurs. So, if you need to do something with the result (show it on the page) then you should do this inside the callback
method.
Here is an edited example with your code:
function read() {
$.get("version.txt?_ts=" + new Date().getTime(), function(data) {
var y1 = parseInt(data[0]);
var y2 = parseInt(data[1]);
var y = (y1*10)+y2;
document.write(y);
});
}
In addition to the asynchronous nature of AJAX, there is another problem with your code. In your read
method, you expect to return a value, but actually it does not return anything. This renders the drr
function to be invalid.
Solution 2:
do like this:
function read()
{
$.get("version.txt?_ts=" + new Date().getTime(), function(data) {
var y1= parseInt(data[0]);
var y2= parseInt(data[1]);
var y= (y1*10)+y2;
document.write(y); /* this is the change, process the result when it's received here */
});
}
function drr()
{
read();
}
also change html to a more proper syntax
<body unload="read();">
generally, when you have $.ajax() call, it is asynchronous - request is made and the success handler is executed, when request is processed successfully.
so if you use return value of the ajax() call, it's not the response received from the server, but rather a request object.
Solution 3:
$.get is async function, there's no return for read function, you need use callback:
function read(callback) {
$.get("version.txt?_ts=" + new Date().getTime(), function(data) {
var y1 = parseInt(data[0]);
var y2 = parseInt(data[1]);
var y = (y1 * 10) + y2;
callback(y);
});
}
function drr() {
read(function(txt) {
document.write(txt);
});
}
Solution 4:
Try this.
function read() {
var result=0;
$.get("version.txt?_ts=" + new Date().getTime(), function (data) {
var y1 = parseInt(data[0]);
var y2 = parseInt(data[1]);
var y = (y1 * 10) + y2;
result=y;
});
return result;
}
function drr() {
var d = read();
document.write(d);
}
Post a Comment for "Function Not Returning Value To Other Function"