objects in the array are undefined [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
Why is the array undefined
My question is how do i get to display the objects inside the results array. I've tried console.log(data.results[0].bodyColor) and i get an error. When i try (data.results) i get undefined. when i try (data.results[0]) it gives responds with a error message. Why is the array undefined when i can see it on my console. [this is the console so how can i print out the value of the AirBagLocFront][1]
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<h2> Vehicle API</h2>
<div id="div"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<!--Jquery CDN-->
<script>
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
cache: true,
data: {
format: "json",
data: "WBAPK5C52AA599960;"
},
dataType: "json",
success: function(data) {
console.log(data.results[0].AirBagLocFront);
}
});
</script>
</body>
</html>

You have a typo in your code. You want Results, not results. Moreover, Results is an array containing a single object. You could traverse the entire data structure quite easily using a for...in loop. Here is a working snippet:
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
cache: true,
data: {
format: "json",
data: "WBAPK5C52AA599960;"
},
dataType: "json",
success: function(data) {
var res = data.Results[0];
for (var prop in res) {
if (res.hasOwnProperty(prop)) {
console.log(prop + ' - ' + (res[prop] ? res[prop] : 'N/A'));
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<h2> Vehicle API</h2>
<div id="div"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<!--Jquery CDN-->
<script>
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
cache: true,
data: {
format: "json",
data: "WBAPK5C52AA599960;"
},
dataType: "json",
success: function(data) {
console.log(data['Results'][0]['BodyClass']);
}
}):
</script>
</body>
</html>
This works the syntax i was using to access the nested object was incorrect. Thanks everyone.

Related

AJAX problems with sending POST, and getting result

Im new at JS and JSON. So I need to send a JSON massive to Google API using POST, and get the answer and show it via alert. I wrote this page, but this code has no result.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Redericting</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
type: "POST",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=KEY',
data: '{wifiAccessPoints:["macAddress", "signalStrength"], cellTowers:["cellId", "locationAreaCode", "mobileCountryCode", "mobileNetworkCode"]}',
dataType: "json",
success: function(response) {
alert(response);
}
});
</script>
</body>
</html>
When using AJAX you require to set the content-type of the information you are sending. By default this value is set to application/x-www-form-urlencoded; charset=UTF-8.
$.ajax({
type: "POST",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=KEY',
data: JSON.stringify({wifiAccessPoints:["macAddress", "signalStrength"], cellTowers:["cellId", "locationAreaCode", "mobileCountryCode", "mobileNetworkCode"]}),
contentType: "json",
success: function(response) {
alert(response);
}
});
Are you sending the response in JSON format? datatype property refers to the type that you're returning from the server. And if that doesn't match, control will go the error callback. Remove or update the datatype property to match the response type. Make the below changes and try
$.ajax({
type: "POST",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=KEY',
data: '{wifiAccessPoints:["macAddress", "signalStrength"], cellTowers:["cellId", "locationAreaCode", "mobileCountryCode", "mobileNetworkCode"]}',
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});

AJAX POST not functioning with jQuery 1.9.0 or greater

Here is my following code for using AJAX calling a static webmethod on ASPX side. It used to work with jQuery 1.2.0 , but I needed to update my jQuery 2.1.1 and now ajax code doesn't even execute as it the code never falls under 'Failure' section
Can somebody nudge me in the right direction please? I have a feeling that I maybe skipping over a reference with the newer version of jQuery?
<%# Register Assembly="System.Web.Ajax" Namespace="System.Web.UI" TagPrefix="asp" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="../Design/jQueryCSS/bootstrap-select.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../Design/scripts/jquery-2.1.1.js"></script>
<script type="text/javascript" src="../Design/scripts/bootstrap-select.js"></script>
<script type="text/javascript" src="../Design/scripts/bootstrap.js"></script>
<link href="../Design/jQueryCSS/bootstrap.css" rel="Stylesheet" type="text/css" />
<script src="../Design/scripts/jquery.columnfilters.js" type="text/javascript"></script>
<script type="text/javascript" src="../Design/scripts/ToolBox.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var rtID = $('#<%=ddlRequestType.ClientID%>');
//console.log(rtID[0].value);
var temp = searchFields(rtID[0].value);
console.log(temp);
});
function searchFields(rtID) {
$.ajax({
type: "POST",
url: "Reports.aspx/Search",
data: JSON.stringify({requestTypeID: rtID}),
//data: 'requestTypeID: "' + rtID + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
/*if (response.d == true) {
console.log(response.data);
}*/
alert("hi");
},
failure: function (response) {
console.log(response.data);
}
});
</script>
Error:
And Yes I did validate requestTypeID value :-)
Try to send a JSON object instead of a String:
$.ajax({
type: "POST",
url: "Reports.aspx/Search",
data: {requestTypeID: rtID}, //Here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
/*if (response.d == true) {
console.log(response.data);
}*/
alert("hi");
},
failure: function (response) {
console.log(response.data);
}
});

Why doesn't my connection to neo4j work (through Javascript)

I am trying to make a interaction with my local neo4j dataset through javascript. But I get this error:
Uncaught SyntaxError: Unexpected token : (13:20:43:754 | error, javascript)
at http://localhost:7474/?callback=jQuery111107695061936974525_1417522841327&{%22statements%22:[{%22statement%22:%22MATCH%20(n)%20RETURN%20count(n)%22}]}&_=1417522841328:2
success (13:20:43:958)
at public_html/index.html:34
I.e. I want to sent and receive queries with a web application.
This is my code by now:
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script language="javascript" type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
var body = JSON.stringify({
statements: [{
statement: 'MATCH (n) RETURN count(n)'
}]
});
$.ajax({
url: "http://localhost:7474",
type: "POST",
data: body,
dataType: "jsonp",
contentType: "application/jsonp"
})
.done(function(result){
console.log(result);
})
.fail(function(error){
console.log(error.statusText);
}); </script>
</head>
It's not working because you're POSTing to the wrong endpoint. Note your URL
Here are the docs.
It should probably be this:
$.ajax({
url: "http://localhost:7474/db/data/transaction/commit",
type: "POST",
data: body,
dataType: "jsonp",
contentType: "application/jsonp"
})

Ajax Json parsed blank result

I am trying to parse some JSON data through AJAX i followed an example from here:
how to parse json data with jquery / javascript?
On the example, they can get it working, but on my exmaple, the turned blank.
I tried just echoing the php, the JSON displayed with no problem either. Wondering what the problem is.
<!DOCTYPE HTML>
<html>
<head>
<link type ="text/css" rel="stylesheet" href= "css/bootstrap.css">
<link type ="text/css" rel="stylesheet" href= "css/account.css">
</head>
<body>
<p id="result">fefe</p>>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$.ajax({
type: 'GET',
url: 'get.php',
data: { get_param: 'value' },
dataType:'json',
success: function (data) {
var names = data
$('#result').html(data);
}
});
</script>
</body>
</html>
What the JSON result looks like in php:
[{"id":"1","userid":"26","title":"654","description":"654"}]
what is the type of data?
try add this line in your code on success function
success: function (data) {
console.log(data);
}
is it an array of objects, if yes maybe you can try this
$.ajax({
type: 'GET',
url: 'get.php',
data: { get_param: 'value' },
dataType:'json',
success: function (data) {
for(var i=0; i<data.length; i++) {
// do your things here using data[i].description until data[i].userid
}
}
});
Try this
$.ajax({
type: "GET",
dataType: "json",
url: "getjobs.php",
data: data,
success: function(data) {
$('#result').html(data);
}
});
Try setting $.ajax's datatype is set to jsonp. Also try to alert the return value.
$.ajax({
type: 'GET',
url: 'get.php',
data: { get_param: 'value' },
dataType:'jsonp',
success: function (data) {
alert('data is ::' +data);
$('#result').html(data);
}
});
Try this:
$.ajax({
type: 'GET',
url: 'get.php',
data: { get_param: 'value' },
dataType:'json',
success: function (data) {
console.log(data);
}
});
in the console(such as chrome browser`s development tools), you can see the actual result.

Jquery Unable to make Ajax Request to Server

I am trying to make an AJAX Request through JQuery
The below is my code .
But when i debugged through Mozilla Firebug i observed that ,there is no Request hitting to the Server .
Could anybody please tell me where i am doing wrong .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JQuery Example</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'ajax/balances',
processData: false,
timeout: 10000,
type: "POST",
contentType: "application/xml",
dataType: "json",
data: '<MyReq user="' + User + '" katha="' + ivalitiKatha + '" />',
success: function(data) {
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});
});
</script>
</body>
</html>
This is my web.xml on server side
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/ajax/*</url-pattern>
</servlet-mapping>
Maybe adding <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> to the head instead of the body helps!
First of all I would recommend moving the CDN JQuery into the head section of the website.
Secondly I have tested the code above and the issue looks to lie with the (data) you are posting in the JSON / AJAX request.
If you remove it or amend to JSON the request returns a result e.g.
$.ajax({
url: 'test',
processData: false,
timeout: 10000,
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"foo": "bar"}',
success: function(data) {
alert('Success');
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});​
You will need to format the data as a JSON request
data: '{"foo": "bar"}',
Hope this helps

Categories