Can't get Data from json object - javascript

I have this script:
<script type="text/javascript">
function requestimg(username){
$.ajax({
url: '{% url "image" %}',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data) {
//Printing the whole data
console.log(data);
//Printing to see where I am
console.log("Name: ");
//Trying to rint the name
console.log(data[0].nombre);
}else {
alert("May Day");
}
}
});
}
I have a problem reading the properties in the json object
When i print the data I get this:
{
json: "[
{
"model": "polls.imagen",
"pk": 17,
"fields": {
"n…"36",
"imagen": "polls/static/pictures/dr.jpg"
}
}
]"
}
And when i print the data as I have it on the code i get:
Uncaught TypeError: Cannot read property 'nombre' of undefined
I have tryied writing it like data.nombre but i just get undefined
I have also tried this console.log(data[0].fields); , data[0].model, data.model
IMPORTANT I want to clarify that i wont know why there are 2 json objects im supposed to get just one and even if i try to put a [1] instead of the [0] i get the same mistakes.
I've tried answers from some previous similar questions and they didn't help.

You will be able to access the fields per
data.json[0].fields
the response of your url is an array, named json
Additionally data.json is returning a string, so convert it to JSON with
data.json = JSON.parse(data.json);

Convert it to JSON first JSON.parse(data.json)
This will give you the access to the fields object data.json[0].fields

Related

Why is Ajax not returning any data? [duplicate]

My script is printing [object Object] as a result of console.log(result).
Can someone please explain how to have console.log print the id and name from result?
$.ajaxSetup({ traditional: true });
var uri = "";
$("#enginesOuputWaiter").show();
$.ajax({
type: "GET",
url: uri,
dataType: "jsonp",
ContentType:'application/javascript',
data :{'text' : article},
error: function(result) {
$("#enginesOuputWaiter").hide();
if(result.statusText === 'success') {
console.log("ok");
console.log(result);
} else {
$("#enginesOuput").text('Invalid query.');
}
}
});
Use console.log(JSON.stringify(result)) to get the JSON in a string format.
EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:
var obj = {id : "007", name : "James Bond"};
console.log(obj); // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj)); //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
console.log(obj.id); //007
}
Try adding JSON.stringify(result) to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

Value showing undefined when trying to output data returned as json from server

I am new to Yii2 framework and PHP.I used Mongo DB as the backend database.I fetched a document from a collection and returned the data as Json from the controller.The data returned back is given below.
{
"55b08c383e1a36233fdbdc06": {
"_id": { "$id": "55b08c383e1a36233fdbdc06" },
"address": [ "abcdgt", "zxcv" ],
"age": "23",
"email": [ "qwert#gmail.com","abcd#mail.com" ],
"location": "kollam",
"name": "ajiths",
"phoneno": [ "9522585456", "7875642256" ] ,
"sex": "male"
}
}
But I am getting 'Undefined' when trying to alert result.name in Javascript code.The code at the front end is given below.
function loadClient(id){
url = "<?= Yii::getAlias('#serverpathweb')?>/client/showclient?id="+id;
$.ajax({
url: url ,
method: "GET",
success: function(result){
alert(result.name);
}
});
}
The code at the controller end is given below.
public function actionShowclient($id) {
$clientdetail = Yii::$app->mongodb->getCollection('client');
$result = $clientdetail->find(["_id" =>$id]);
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $result;
}
Can anyone tell me how to get the value result.name.
your getting JSON result with id as key so access ur JSON data like this
first get the key of ur JSON using Object.keys
next using key print the values you need
var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name
Note if you are getting multiple user details please let me know
Your "result" object is probably a String because you're not telling jQuery otherwise. Trying adding the option dataType:json to your request as in:
$.ajax({ url: url, method: 'GET', dataType: 'json', etc...
Edit: It also looks like there's a simple bug in your code. You need to access your property where it's nested in the resulting object:
result[id].name

How to add the new JSON from existing JSON file

I searched here get few related posts found but not helpful. I created one json file it has some text i want to append some more json in that using javascript(JSON stored in locally).
I have json file like this:
{ "Home": [ "a", "b", "c" ] }
i want to include this text "Log": 1
want to achieve like this,
{ "Home": [ "a", "b", "c" ], "Log": 1 }
Now I have like this in my json file(currently i have but json format is not correct)
{ "Home": [ "a", "b", "c" ] }
{ "Log": 1 }
$.getJSON('myfile.json', function(data) {
alert("success");
}.error(function(data){
alert(JSON.stringify(data));
});
this returns parser error. I know the JSON format is wrong. Please guide me to create a correct JSON format.
The error is in both versions of the JSON. You are missing the " at the start of the string c.
http://jsonlint.com/ will help you track down where errors in JSON occur.
As a rule of thumb, you should create JSON using a JSON serializer in a mature library and not by hand or string concatenation.
Now i have like this in my json file
That's completely wrong. The code you had in "Now i want to achieve like this" was right (aside from the error mentioned above).
You need to read your JSON, parse it into a JS object, edit the object, and convert back into JSON before writing:
assuming myfile.json contains:
{ "Home": [ "a", "b", "c" ] }
$.getJSON('myfile.json', function(data) {
alert("success");
obj = JSON.parse(data);
obj.log = 1;
writeJSON(JSON.stringify(obj));
}.error(function(data){
alert(JSON.stringify(data));
});
and writeJSON will be something like:
function writeJSON(jsonString)
$.ajax({
type: 'POST',
url: 'myfile.json',
data: jsonString,
success: function(data) { alert('write succesful!'); },
contentType: "application/json",
dataType: 'json'
});
}
assuming that you are using a server which can both read and write via this endpoint.

Issue with JSON.stringify adding a extra \ and "" to my Json object

Hi I am creating using Javascript an array of object with a key and a value using the following code.
ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });
As a result I have am array of object like this:
key:29; value: 'Country'
Key:12; value: '4,3,5'
when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify
var jObject = JSON.stringify(ValuesArray);
My JSON now which is wrong is:
{
"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"
}
I would like to have a JSON object like this
{
"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]
}
without the quotes around the [] and the character \
Any good idea to solve it.
Thank you
More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:
function PostAPIRequest(address) {
var jObject = JSON.stringify(ValuesArray);
var responseJson = null;
$.ajax({
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
ProcessDataResponse(responseJson);
//TODO: REFRESH THE DATA GRID
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.
alert(xhr.status);
alert(thrownError);
}
})
}
and this how I am receiving it in my API controller
...
// POST api/datavalues/5
public string Post(int id, JObject value)
{
var temp = value;
...
It looks like you are placing a string as the value in your map. You should do something like:
var objMap = {"JObject" : ValuesArray};
var json = JSON.stringify(objMap)
What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.
EDIT
It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for - http://jsfiddle.net/4G5nF/
In your post request, try this
var jObject = {"JObject" : ValuesArray};
$.ajax({ url: address,
type: 'POST',
dataType: 'json',
data: jObject,
success: function (data) { .. }});
Note the change in the data attribute. That is a value that is automatically JSONified for you.
const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))
"{\"a\": 1, \"b\": 2}"
May be you have an old prototype library.
As I remove it, bug has disappeared

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Categories