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

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);
},

Related

Can't access nested objects sent to Flask as an AJAX POST request [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
How to get POSTed JSON in Flask?
(13 answers)
Closed 5 years ago.
I am trying to POST an object to Flask using AJAX. When the object is simple the code works fine but when when the object includes a nested object Flask receives the data in a weird format.
Here is the AJAX POST:
var req = "commit_url";
var data = {"longURL":"www.google.com",
"product":"FIN",
"project":"Zeus",
"platform":"Twitter",
"theme":["Tech"],
"owner":"Tom"};
var submitData = {"req":req, "data":data};
console.log(submitData)
$.ajax({
url: "http://xxx.xxx.xxx.xxx:5000/",
data: submitData,
type: 'POST',
success: function(response) {
var result = JSON.parse(response);
printShortURL(result.shortURL);
},
error: function(error) {
alert("Error contacting the server. See console for details.")
console.log(error);
}
});
When I submit the data the console shows this:
{"req":"commit_url","data":{"longURL":"www.google.com","product":"FIN","project":"Zeus","platform":"Twitter","theme":"["#Tech"]","owner":"Tom"}}
Here is the python in Flask:
#app.route("/", methods=['POST'])
def getData():
f = request.form;
print f
req = f['req'];
print req
longURL = request.form['data[longURL]'];
print longURL
product = request.form['data']['product'];
print product
shortURL = '4Fi92v';
return json.dumps({'status':'OK','shortURL':shortURL});
Here is the result that I get in Flask:
ImmutableMultiDict([('data[longURL]', u'www.google.com'), ('data[project]', u'Zeus'), ('data[theme][]', u'#Tech'), ('data[owner]', u'Tom'), ('data[product]', u'FIN'), ('req', u'commit_url'), ('data[platform]', u'Twitter')])
commit_url
www.google.com
xxx.xxx.xxx.xxx - - [06/Feb/2018 12:21:08] "POST / HTTP/1.1" 400 -
As you see it's changing the key to 'data[project]' rather than preserving 'data' as an object. I can access the data but I would like to be able to pass the whole 'data' object to another function without having to go through all the variables.
I'm pretty sure the problem is with the javascript but I tried using JSON.parse and JSON.stringify but I've had no success.
send data as a json string do a JSON.stringify.and in the backend you are getting the ImmutableMultiDict object to convert it to dict.user the to_dict() method.
var req = "commit_url";
var data = {"longURL":"www.google.com",
"product":"FIN",
"project":"Zeus",
"platform":"Twitter",
"theme":["Tech"],
"owner":"Tom"};
var submitData = {"req":req, "data":data};
console.log(submitData)
$.ajax({
url: "http://xxx.xxx.xxx.xxx:5000/",
data: JSON.stringify(submitData),
type: 'POST',
success: function(response) {
var result = JSON.parse(response);
printShortURL(result.shortURL);
},
error: function(error) {
alert("Error contacting the server. See console for details.")
console.log(error);
}
});
then in your backend do
#app.route("/", methods=['POST'])
def getData():
f = request.form.to_dict();
print f
req = f['req'];
print req
longURL = f['data'];
print longURL
print product
shortURL = '4Fi92v';
return json.dumps({'status':'OK','shortURL':shortURL});

JS Array values become undefined [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 function that pull information from an XML file located on the system. IT will then pull the values located in that file and put them into an array. Once the function is called the values enter the array, but then onnce the function ends the values go away.
function getXML(location,day){
$(document).ready(function () {
$.ajax({
type:'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain:true,
url: './../CurrentFiles/'+ location +'.xml', // name of file you want to parse
success: function (xmldata){
if(array[0] == null){
$(xmldata).find('dgauges').children().each(function(){
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
});
return array[day];
}
From what I researched it could be a problem with async, but I do not understand entirely what that is.
Also I am very new to jquery so if there is any thing that seems out of place that's why.
THis is what my plan is for this function
I have an XML file formatted like
<dgages><d>26.850</d><d-1>7.70</d-1><d-2>2.00</d-2><d-3>27.90</d-3></dgages>
I am trying to pull all of those values in an array so I can do some calculations on them.
Get the XML Document
find all the children of dgage
put each of the children into the array
4 once the array is filled return the associated day.
Try making a synchronous call instead. AJAX calls are async by default, which means that code will jump to the next line before waiting for the result of the previous line. You can enforce the result by telling the AJAX call to do it synchoronously:
function getXML(location, day) {
var array = [];
$.ajax({
type: 'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain: true,
async: false, // Wait until AJAX call is completed
url: './../CurrentFiles/' + location + '.xml', // name of file you want to parse
success: function(xmldata) {
if (array[0] == null) {
$(xmldata).find('dgauges').children().each(function() {
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
return array[day];
}

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);
});

Get value from php to javascript using ajax [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 the following ajax script
dataString = 'cipher'; //
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
returnedvalue = result //I wanted to store the value returned by php in this variable
alert(returnedvalue);
and the tokenize.php is
$data = json_decode(stripslashes($_POST['data']));
return $data; //Pass this value as ajaxs response
But im not able to get this.When I checked in the console I get error uncaught:result is not defined.
Im new to query,searched on google and done upto this.
The json is not necessary,all I wanted to do is pass a value to php and process it and give a rssponse back to teh javascript so that i can use it in the javascript
You are passing just string(dataString = 'cipher';) into ajax file. There is no need to JSON.
To use echo for return values from AJAX file.
Update in JS:
dataString = 'cipher'; //
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(result) { //just add the result as argument in success anonymous function
var returnedvalue = result;
alert(returnedvalue);
}
});
Update in PHP file:
$data = stripslashes($_POST['data']);
echo $data;
You need to pass the parameter into the anonymous function for the success event.
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}

Returning value from javascript 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 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/

Categories

Resources