Revealing module pattern method echo undefined - javascript

I wrote this function as revealing module pattern, but when I call the get method in console by metadataModule.get(); it echoes undefined in console.
var metadataModule = function () {
var metadataurl = 'http://farskids326.com/data.json';
function getMetadata() {
console.log("Metadata Function Called")
$.ajax({
url: metadataurl,
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
return {
get: getMetadata,
};
}();
Where did I made a mistake in this code?

When you are working in the console, the return value of the last expresion is echoed after any command. The method you are using doesn't have an explicit return value. So, that may be why you see undefined.
This probably means that your ajax call is encountering an error. Try changing it to log when either success or error happens, like so:
$.ajax({
url: metadataurl ,
dataType: "json",
success: function(data){
console.log('called success!');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('called error!');
}
});
Then, when you run your code, you should see exactly which callback is being executed. Hopefully, that will give you a good starting point for debugging the issue.

The getMetadata function returns nothing so yes, it will output undefined. for it to respond with the content of the JSON you need to make the ajax call synchronous and return the value you get.
var metadataModule = function () {
var metadataurl = 'http://farskids326.com/data.json';
function getMetadata() {
console.log("Metadata Function Called")
var content = {}
$.ajax({
url: metadataurl,
async : false,
dataType: "json",
success: function (data) {
content = data;
}
});
return content
}
return {
get: getMetadata,
};
}();

Related

Assign function to value in Javascript

Good Day,
I try to assign to a variable the result of an Ajax request. I tried both of the requests below, with no result (got an "Undefined" answer).
I don't understand the difference between:
var temp = obj.method(me, you);
and
var temp = (function () {
obj.method(me, you);
})();
Here is the AJAX request:
ObjID.prototype.getAjx = function(one, you){
$.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
}
Is this the same, or not ?
Thanks for your help! :)
The first two bits of code you showed effectively do the same thing.
However, neither of them do what you think they do. Neither of them are assigning the return value from your AJAX call anywhere:
The first line of your code:
ObjID.prototype.getAjx = function(one, you){
is simply assigning the function that contains the actual AJAX call to the .getAjx property of the ObjID.prototype. That function doesn't contain any return statements and upon execution, will not return anything. That is why you are getting undefined.
The code that actually performs the AJAX call is:
$.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
and, you aren't assigning that return value to anything. If you wanted to, you'd need to write something like this:
var result = $.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
JQuery AJAX calls return a reference to a Promise object and that's what you would be storing in that case.

Getting Data from Ajax request displayed

I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});

Jquery Asynchronous call return undefined value

I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.
funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
url: path,
type: method,
data: params,
async: false,
beforeSend: function() {
$('.black_overlay').show();
},
success: function(data){
console.log(data);
resp = callbackFunction(data, obj);
if(alerter==0){
if(obj==null) {
resp=data;
} else {
obj.innerHTML=data;
}
} else {
alert(data);
}
},
error : function(error) {
console.log(error);
},
complete: function() {
removeOverlay();
},
dataType: "html"
});
return resp;
}
The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.
In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.
Is there any way to solve both problems? I would get beforeSend function and resp value both.
Thanks
Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:
var resp = '';
$('.black_overlay').show();
$.ajax({
...
Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.
Take the resp variable out from the function
Create one extra function respHasChanged()
when you get the data successfully, use the code
resp = data;respHasChanged();
You can restructure on this way, (why no use it in async way?)
function ajaxCall(path, method, params) {
return $.ajax({
url: path,
type: method,
data: params,
beforeSend: function() {
$('.black_overlay').show();
},
dataType: "html"
});
}
Call in your javascript file
ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
.done(function(data) {
console.log(data);
// DO WHAT YOU WANT TO DO
if (alerter == 0 && obj !== null) {
obj.innerHTML = data;
} else {
alert(data);
}
}).fail(function(error) {
console.log(error);
}).always(function() {
removeOverlay();
});

Ajax callbacks didn't return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Im trying to create an ajax function to get some params of the DB each time, but when I call the ajax method it is not returning correctly, when I do it debug the value was ok, but the return result isn't works.
$(document).ready(function () {
function foo(mod){
var uri="some url";
$.ajax({
type: "GET",
url: uri,
}).done(function( data ) {
return data;
});
}
// alert to get the result is always printing undefined
alert(foo("param_1"));
});
foo can't return the result of the ajax call, because the ajax call is asynchronous. foo returns before the call completes. Moreover, the return in your done handler returns from the done handler, not foo.
You'll need to have foo accept a callback, and then call that:
$(document).ready(function () {
function foo(mod, callback){
var uri="some url";
$.ajax({
type: "GET",
url: uri,
}).done(function( data ) {
callback(data);
});
}
// alert to get the result is always printing undefined
foo("param_1", function( data ) {
alert(data);
});
});
Or if you're really do no processing on it at all before giving it to the callback, you could supply callback to done directly:
$(document).ready(function () {
function foo(mod, callback){
var uri="some url";
$.ajax({
type: "GET",
url: uri,
}).done(callback);
}
// alert to get the result is always printing undefined
foo("param_1", function( data ) {
alert(data);
});
});
You can set async as false, but instead I recommend you to implement success and error handlers that can work async
$(document).ready(function() {
function foo(mod) {
var uri = "some url";
$.ajax({
type: "GET",
url: uri,
success: successHandler,
error: errorHandler
});
}
function successHandler(data, textStatus, xhr) {
// Handle your data here
console.log(data);
//alert(data);
}
function errorHandler(xhr, textStatus, errorThrown) {
// Magic
}
// alert to get the result is always printing undefined
//alert(foo("param_1"));
foo("param_1");
});

JQuery Ajax call, return value problem

function getMore(from){
var initData = "&start-index=";
initData += from;
$.ajax({
type:"POST",
url: '', //removed the URL
data: initData,
dataType: 'json',
success: function(result) {
return result;
},
error: function(errorThrown) {
}
});
return result;
}
Its a google base query; I have another function that makes the initial server call and gets the first 250 items. I then have a running counter and as long as the results = 250 it calls the server again, but starting at "start-index=" of the current amount of items pulled off. This part all works correctly and with firebug I can also see that the server response is proper JSON.
The trouble I'm having is trying to return the JSON from this function to the function that called it. I do not want to call the original function again because it will clear the arrays of data already pulled from the server. Each time it returns to the parent function it's null.
Does anyone know how i can go about returning the data using "return"?
function FuncionCallGetMore(){
//...
getMore('x-value', FuncionGetReturn);
//...
}
function FuncionGetReturn(error, value){
if (!error) {
// work value
}
}
function getMore(from, fn){
var initData = "&start-index=" + from;
$.ajax({
type:"POST",
url: '', //removed the URL
data: initData,
dataType: 'json',
success: function(result) {
fn(false, result);
},
error: function(errorThrown) {
fn(true);
}
});
return;
}
The only way that you can do what you're describing is to make the AJAX call synchronous, which you don't want to do since it will lock the UI thread while the request is being made, and the browser may will to freeze. No one likes freezing.
What you want to do is use callbacks. Post the code of the other functions involved so I can get a better idea of what is going on. But basically, what you want to do is to create an asynchronous loop.
function listBuilder() {
var onError = function(response) {
// ...
};
var onSuccess = function(response) {
// Handle the items returned here
// There are more items to be had, get them and repeat
if ( response.length == 250 ) {
getMore(onSuccess, onError, 250);
}
};
getInitialSet(onSuccess, onError);
}
function getMore(onSuccess, onError, from) {
$.ajax({
type:"POST",
url: '', //removed the URL
data: "&start-index=" + from,
dataType: 'json',
success: onSuccess,
error: onError
});
}

Categories

Resources