Returning value from javascript object [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have created a javascript object and im trying to fetch som data from it.
Im using jquery ajax to fetch send some values and then returing them from a php script.
this works, but when i try to use an instanse of my javascript object to dispaly the value i get 'undefined'.
Object:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
success: function(data){
callback(data);
},
error: function(event){
alert(event.error);
}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
console.log(data); //Works
return data;
});
},
}
})();
in my other script:
var obj = getDBresults;
var data = obj.getAllVideoes(); //this runs, and produce the log showed above
console.log(data) //results in undefined
console.log(obj.getAllVideoes()) //results in undefined

Maybe you can use callbacks it will solve your async problems: http://recurial.com/programming/understanding-callback-functions-in-javascript/

Related

ajax success data assignment to variables with data[0] is undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am trying to select data from a database in javascript code using ajax which calls a php script with a mysql query. The pgp code is working correctly, as I can view the ajax success results with an alert. But when I try to assign the data to variables, they show in the Console as undefined or NaN. Here is my code:
function zoomBldg() {
bldgId = document.getElementById("bldgzoom").value;
var bldgStreetAddress,zoomLat,zoomLng,bldgDescription,bldgDefaultPic,zoomCenter;
console.log('bldgId',bldgId);
$.ajax({
url: "getBldgInfoWajaxGETtest.php",
type: "POST",
data: {bldgId : bldgId},
dataType: 'json',
cache: false,
success: function(data)
{
alert(JSON.stringify(data));
bldgStreetAddress = data[0];
zoomLat = data[1];
zoomLng = data[2];
bldgDefaultPic = data[3];
},
error: function (request, status, error) {
console.log(error);
}
});
zoomLat = parseFloat(zoomLat);
zoomLng = parseFloat(zoomLng);
zoomCenter = {lat:zoomLat, lng:zoomLng};
console.log('bldgId',bldgId);
console.log('bldgStreetAddress',bldgStreetAddress);
console.log('zoomLat',zoomLat);
console.log('zoomLng',zoomLng);
}
The results that appear in the alert is:
[{"0":"50 Fremont Street","1":"37.790505","2":"-122.397259","3":null,"building_address":"50 Fremont Street","latitude":"37.790505","longitude":"-122.397259","default_pic":null}]
The results in the Console are:
bldgId 17
bldgId 17
bldgStreetAddress undefined
zoomLat NaN
zoomLng NaN
I copied the data[0] etc code from an example online, but I am not too familiar with json so I'm not sure why that isn't working.
Understand the code your copying and pasting. Learn how json works and what JSON.parse and JSON.stringify do.
Look at your json structure.
The information is in an array.
so data is an array. Each key of the object is a string not a integer.
data[0]["1"]
You also have the success function being called later on. Thus the values would not be set. To fix this I would do any code that needs the values in or from the success callback.
success: function(data)
{
alert(JSON.stringify(data));
bldgStreetAddress = data[0]["0"];
zoomLat = data[0]["1"];
zoomLng = data[0]["2"];
bldgDefaultPic = data[0]["3"];
zoomLat = parseFloat(zoomLat);
zoomLng = parseFloat(zoomLng);
zoomCenter = {lat:zoomLat, lng:zoomLng};
console.log('bldgId',bldgId);
console.log('bldgStreetAddress',bldgStreetAddress);
console.log('zoomLat',zoomLat);
console.log('zoomLng',zoomLng);
},

variable returns undefined when attempting to read a file using ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Hello i am getting undefined when reading a json file using ajax file. It returns undefined:
var input;
$.getJSON('cake.json', function(data) {
input = data;
});
console.log('Result'+input);
but the variable input returns undefined.
You have this:
var input = [];
$.getJSON('cake.json', function(data) {
input = data;
});
// This will likely execute BEFORE getJSON has returned 'data'
console.log('Result' + input);
But try this and, assuming you're actually getting data, you should see results in the console.
var input = [];
$.getJSON('cake.json', function(data) {
input = data;
console.log('Result' + input);
});
(Another way to debug to make sure your JSON call is working is to use the network debugger.)
If you don't need input to be in the global scope (see here about scope of variables in JavaScript), you can just do this:
$.getJSON('cake.json', function(data) {
// do something with the 'data'
});
or:
$.getJSON('cake.json', function(data) {
process(data);
});
function process(data) {
// do something with data
}

How to return data to variable after ajax call success [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a PHP file returning data in required array format to my FlotChart, it's working.
Now I'm trying to get this result in my script using ajax, however I cannot see result on global variable, as described below:
myJS.js
var EcomDashboard = function() {
return {
init: function() {
var dataEarnings = NULL;
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
alert(data); //show my array [ [1, 20],[2,30],[3,14] ]
dataEarnings = data;
}
});
alert(dataEarnings); //showing "NULL" but I need [ [1, 20],[2,30],[3,14] ]
...
What is the correct way to assign to my variable date Earnings the array [[1, 20], [2.30], [3.14]]?
Javascript is an async language, it means it won't wait the http request to finish to execute the next line. you will have to assign the variable inside the success block.
the alert shows null is becauseit got executed before the $.ajax http request line finishes.
may be you can do this using a callback:
dataAccess.js
var ecomDashboard = function() {
init: function(callback) {
var dataEarnings = NULL;
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
callback(data);
}
});
}
}
controller.js
ecomDashboard.init(function(data){
// data contains the array result
// do your stuff
})
event better:
since jquery 1.5 there is incorporated promise interface, and .success is going to be deprecated. edited: thanks to Kevin B
so with promise:
dataAccess.js
var ecomDashboard = function() {
init: function(callback) {
var dataEarnings = NULL;
return $.ajax({
url:"operation.php",
dataType: "text"
});
}
}
controller.js
ecomDashboard.init().done(function(data){
//do your stuff
alert(data);
}).fail(function(error){
//do stuff when error
});
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
doSomthingOnComplete(data);
}
});
function doSomthingOnComplete(data)
{
// do here your work
}
This is occurring because that alert(dataEarnings) is executing before your ajax request resolves. The first letter in the AJAX acronym is Asynchronous. So, ultimately your data is being set properly you are just trying to access it before the asynchronous call completes.

How to return data from ajax call JQuery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a webapi in asp.net that gives me back JSON code. I want to access this with JQuery in a php-website.
I have this JQuery code to get the data from the webapi:
$.ajax({
type: 'GET',
url: 'localhost/webapi/api/data'
}).done(function (data) {
});
How can I return the value of 'data' to a global variable? So that I have a list of objects where I can loop through with navigation buttons.
Example:
When I click on the nextButton, I want to get the value of data[1].Text.
$('#nextButton').click(function() {
data[1].Text;
});
Perhaps like this:
var dataContainer = {}; // if you work with strings use ''
$.ajax({
type: 'GET',
url: 'localhost/webapi/api/data'
}).done(function (data) {
dataContainer = data;
});
$('#nextButton').click(function() {
if(dataContainer != {}){ // for strings != ''
// use dataContainer
}
});

AJAX response into an object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a stringified array of objects in a database that I'm retreiving with an $.ajax call. I'm trying to use a callback function to get that data into an array outside of my ajax function.
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
function dataHandler(data){
console.log(JSON.parse(data));
return JSON.parse(data);
}
var loadedMap = getMap();
console.log(loadedMap);
The console.log inside of the dataHandler function shows up in my Javascript console as a standard Array (clickable, can view all the data). The console.log at the very end shows up in the console as [object Object]. I can see the actual data inside of that object in a "responseJSON" field, but I can't seem to correctly get that into the loadedMap array.
What am I missing here?
Edit: I feel like my question is different from all of the answers to other questions. Mine seems to be more of a scope problem. A lot of the answers advocated the .done and .fail ways to handle AJAX.
var loadedMap = [];
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap = r;
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
console.log(loadedMap);
This code successfully gets the array where "loadedMap = r", but when you console.log the loadedMap on the outside, its undefined. How can we get the actual data to be outside the AJAX functions?
The function getMap does not return the response, it just calls dataHandler when the response arrives.
create a global variable and assign the vallue of the JSON.parse(data) to that variable. :
var myData;
function getMap(){
...
});
};
function dataHandler(data){
console.log(JSON.parse(data));
myData = JSON.parse(data);
}
getMap();
JQuery's AJAX returns a promise, so you can either go the callback route, as it looks like you were trying to do, or you can simplify it with promises:
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
getMap().then(function(data){
loadedMap = JSON.parse(data);
console.log(loadedMap);
});

Categories

Resources