Undefined when trying to parse JSON - javascript

I'm trying to parse a JSON response with JQuery:
<script>
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url : 'test.php',
type : 'GET',
data : {
name : "Peter",
},
dataType : 'json',
success : function(response) {
console.log(response);
alert(response.name)
},
error : function() {
console.log("error")
}
});
});
});
</script>
I want to get the name into the alert box, but everything I get is an undefined.
This is the result in the console:
Object {results: Array[1]}
results: Array[1]
0: Object
id: "4"
name: "Peter"
When I do alert(JSON.stringify(response)); I get {"results":[{"id":"4","name":"Peter"}]}, so there is definitely valid JSON.

In response there is not property name. name there is in in first element in results array, so to get name you need do
console.log(response.results[0].name)

response is an object which contains an array in results, you need to iterate over ressponse.results or if you're sure it well have only one element, use response.results[0].name

The JSON data contains an array, so you need use an index:
var data = {"results":[{"id":"4","name":"Peter"}]}
document.write(data.results[0].name)

Related

pasring JSON from string in jQuery

http://localhost/project1/index.php
//AJAX region
$(function(){
$.ajax({
type : 'GET',
url : 'https://jsonplaceholder.typicode.com/posts/1',
success : function(data){
console.log('success \n', data);
},
error : function(data){
console.log('error', data);
}
});
});//AJAX region
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
it's easily loading data from http://localhost/project1/json.php
console:
data is string, if I use $.parseJSON(data) or JSON.parse(data) i get following error...
I want data as realtime JSON object, so that I can access each properties & values.
Observation 1: unnecessary parseJSON
No need to call parseJSON.
Use dataType property of $.ajax to load your data directly in JSON format:
$.ajax({
type : 'GET',
dataType: 'json', // here
url : 'http://localhost/project1/region.php',
success : function(data) {
// data is already a JS object :)
console.log('success \n', data);
},
error : function(data){
console.log('error', data);
}
});
Observation 2: wrong JSON
Code above will still throw the same error, because of
unexpected token ,
It refers to the trailing comma after all the last elements your object and its children. Remove that comma and there will be no more errors.
For example:
"State1" : {
"City 1",
"City 2",
"City 3",
}
There should NOT be a comma after "City 3". The same goes for other states, and for whole "country2" object too.
There is another error: your States objects are arrays, but you are writing then as objects. Change curl brackets to square brackets for "State1" and "State2".
The json object you are returning is invalid json, for the state objects, you need to make them arrays. so:
"State1":["City1","City2","City3"]
When the parser parses this object it expects a second value per city like "City1 ": "Second Value"...since there is no second value its breaking.

Access array-elements inside JSON-object

I have the following json-object returned via response
the function
function getUserList() {
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "paul rudd",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response); // prints the object
}
});
}
My question is how the movies-array are accessed in javascript? I cannot access it via response - if I do i get "undefined" returned.
i.e response.movies
undefined
or response.movies[0]
uncaught typerror cannot read property [0] of undefined
The property of the object appears to be "movies[]", not "movies", for which you can use bracket notation to get the value of
console.log(response["movies[]"][0])
Try response['movies[]']. Also, you could console log the response object and inspect what is inside it
in your back end you're returning with bad naming , so
to access that array you've to access it as below response.["movies[]"]
see below sample :
response = { "movies[]": ["1","2","3"] };
console.log(response["movies[]"]);
movies is array, use $.each or .forEach()
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "paul rudd",
movies: ["I Love You Man", "Role Models"]
},
success: function(response) {
$.each(response.movies, function(index, value){
// prints the object
console.log(value);
})
}
});

Parsing response text as key value pairs in an elegant way

Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....
I have a an ajax call:
$.ajax({
url: "/events/instructor/",
type: 'POST',
data: {
instructorID: $(this).attr("id")
},
complete: function (data) {
$("#name").html(data["responseText"]["name"]);
$("#email").html(data["responseText"]["email"]);
$("#photo").html(data["responseText"]["photo"]);
$("#summary").html(data["responseText"]["summary"]);
$("#url").html(data["responseText"]["url"]);
}
});
The data being returned is encoded in JSON by the server (C#).
Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.
How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?
i think you need to parse json first. look at the api.jquery.com/jquery.parsejson
// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"
P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?
success: function(data) {
console.log("response is good", data);
},
error: function (){
console.log("something is went wrong");
}
try using like this:
complete: function (data) {
var data=JSON.parse(data);
$("#name").html(data.responseText.name);
$("#email").html(data.responseText.email);
$("#photo").html(data.responseText.photo);
$("#summary").html(data.responseText.summary);
$("#url").html(data.responseText.url);
}
to get only correct response use success.

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

Javascript array converted to JSON objects instead of array

I am trying to submit some JSON to my web app and I want the JSON to be like this:
{
"thing1" :
{
"something" : "hello"
},
"list_of_things" :
[
{
"item1" : "hello"
},
{
"item2" : "hello"
}
]
}
Here I have one JSON object and a JSON array that holds JSON objects. When I create the data to submit in Javascript I do:
form = {
"thing1" : {
"something" : somethingVariable
},
"list_of_things" : listArray
}
Here 'listArray' is a Javascript Array object of Javascript hash objects. I submit this using jQuery's ajax method but instead of javascript array displaying as the JSON array desired it converts it to a series of JSON objects like this:
{ "1" : { "thing1" : "something" }, "2" : { "thing2" : "something" }...
How can I get the array to be submitted as an array rather than be converted into a series of JSON objects with the array indexes as keys?
EDIT#1: 'listArray' is a simple Javascript array that is defined like so:
var listArray = new Array();
listArray.push({ "thing1" : "something" });
listArray.push({ "thing2" : "something" });
EDIT#2: 'form' is sent to the server with the following call:
$.ajax({
type: 'POST',
url: '/url',
dataType: "json",
data: form,
success: function(data) {
/* success code here */
}
});
Have a look here. If you are truly trying to post JSON you will need to send the string, not an object literal. You could use JSON.stringify (or a more supported JSON solution) on form.
$.ajax({
url: "/url",,
dataType: "json",
type: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify(form)
});

Categories

Resources