Array of arrays json Javascript, ajax response - javascript

Im trying to access to parameter value from response.
$.ajax({
type: "POST",
url: "",
dataType: 'text',
async: false,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: '{ "action" : "create", "resource" : {"name" : "teddssssssssddsssdsddddsdddwdsdssdsddi", "description": "Test Tenant Description","parent": {"href": "localhost"}}}',
success: function(as) {
alert(as[0][0]["id"]);
}
});
in the success area i got the response, in json. I want to access to the id value, but i cant. always says undefined, i tried different options.
this is the response format.
{
"results": [
{
"href": "localhost/1111111",
"id": "100000000111",
"name": "test",
"ancestry": "1000011111",
"divisible": true,
"description": "Test Tenant Description",
"use_config_for_attributes": false,
"default_miq_group_id": "10021200000173"
}
]
}
I dont know if i can access direct to the parameter or better get the response as text and split.

The response has a different structure.
Your response is an object with one property and value is an array of objects.
something like {'results': [...{}]}
Key 0 does not exist.
const data = {"results":[{"href":"localhost/1111111","id":"100000000111","name":"test","ancestry":"1000011111","divisible":true,"description":"Test Tenant Description","use_config_for_attributes":false,"default_miq_group_id":"10021200000173"}]};
console.log(data.results[0].id);

Related

Unexpected end of JSON input whilr trying to post it to the sever

Whenever I am trying to send a JSON object to server it gives me this particular error.
This is my Javascript code where I send the above JSON object to the action class but getting this error:
error: [object Object] status: parsererror er:SyntaxError: Unexpected end of JSON input
I need to understand what should be my JSON format? Is it OK or are changes required?
function openLOV(obj) {
var requestData = {
objId : "productLOV",
attributes : [ {
label : "URL_ID",
column : "URL_ID",
visible : "N"
}, {
label : "URL",
column : "URL",
visible : "Y"
}],
searchKey : "obj.value",
queryKey : "SQL_GET_PRODUCT",
callback : "cb"
};
var requestJSONData = JSON.stringify(requestData);
alert(requestJSONData);
var encrUrl = crcEncodeUrl("/EPSWeb/util/lovAction.do?mode=init&element="+obj.id);
$.ajax({
type : "POST",
url : encrUrl,
dataType: 'json',
contentType : "application/json",
data : requestJSONData,
success : function(response) {
$("#_lov_modal").remove();
createLOVModal();
$("#lovContent").html(response);
$("#btnLOVModal").click();
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
Its a data issue in the JSON you are sending to server,
in your variable requestData you need to add double quotes to the key fields, that makes the JSON valid. As mentioned below.
var requestData = {
"objId": "productLOV",
"attributes": [{
"label": "URL_ID",
"column": "URL_ID",
"visible": "N"
},{
"label": "URL",
"column": "URL",
"visible": "Y"
}],
"searchKey": "obj.value",
"queryKey": "SQL_GET_PRODUCT",
"callback": "cb"
}
This would work.

Arrays in AJAX request JSON object data

I am sending a request to a Node/Express server using jQuery thats data is a JSON object containing an array:
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: data,
dataType: 'json'
});
The request itself is working fine, however the server is reporting the data as:
{
name: 'James Jamesy',
'children[0][name]': 'Little James',
'children[0][age]': '4',
'children[1][name]': 'Medium James',
'children[1][age]': '6',
'children[2][name]': 'Graham',
'children[2][age]': '8'
}
Now I've figured out that I can get my desired result by instead stringifying the children array:
var data = {
"name": "James Jamesy",
"children": JSON.stringify([ ... ])
}
And then JSON.parse()ing it on the server.
However I am hoping someone can explain why the array is converted as it is in the request, and whether I should be handling this a different way? As in this instance converting the single array is fine, but going forward I might have semi-complex objects I'm looking to send to the server.
Thanks in advance!
EDIT: Additionally and strangely(?), if I send the JSON result back as the passed JSON, it works perfectly:
res.json(JSON.parse(req.body.categories));
The browser logs out the object and I can manipulate it perfectly fine.
You weren't passing a JSON string through ajax which is why you couldn't handle the data on the back end.
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: JSON.stringify(data),
contentType: 'application/json', // for request
dataType: 'json' // for response
});

Cant retrieve the JSON using Ajax

My JSON:
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
Ajax call:
$.ajax({
type: "POST",
url: my_url,
async: false,
success: function(result){
alert(JSON.stringify(result));
message= JSON.parse(result);
alert(message.Schedule.channel.length);
}
});
My json is coming. First alert message is giving my JSON. When i parse that json, error is coming like
Uncaught SyntaxError: Unexpected token o
Location: jquery.min.js.2
I tried solving this issue. Couldnt able to figure out where it is going wrong.
Can anyone help me
Remove the comas after "prepaid_price": 15 and "prepaid_price": 7. You are also missing a closing } at the end of your JSON.
You can validate your JSON here: http://www.jsoneditoronline.org/
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
You can use dataType: 'json', in your AJAX-call, then your JSON will be parsed automatically and you don't need to call message = JSON.parse(result); because your result will be already an Object.
Then you can call alert(result.Schedule.channel.length); direct.
Your code would look like:
$.ajax({
type: "POST",
url: my_url,
async: false,
dataType: 'json',
success: function(result){
alert(result.Schedule.channel.length);
}
});

Attempting to parse or assign JSON response: Response is read as [object Object] [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Using Flickr API, Javascript/JQuery, and AJAX, I have the follow code:
function getRequest(arguments)
{
var requestinfo;
$.ajax({
type: 'GET',
url: flickrurl + '&'+ arguments + '&jsoncallback=jsonCallback',
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (json)
{
requestinfo = json;
//Parse attempt requestinfo = $.parseJSON(json);
//Old method return json;
}
});
return requestinfo;
}
When the response is received and I attempt to assign the json (the response) data to the variable, requestinfo, (or even if I do a straight 'return json' line) I get an error indicating the returned value is undefined. Upon fooling with the success function, I notice that any attempts to parse the response fails due to 'json' being read as [object Object] instead of the JSON response.
Is the response already in array format? If not, how can I get it to that point?
Here is an example JSON response (there are multiple types as different requests are needed to receive all needed information (Flickr API):
{
"collections": {
"collection": [
{
"id": "122388635-72157643471284884",
"title": "Test Gallery 2",
"description": "Test 2",
"iconlarge": "/images/collection_default_l.gif",
"iconsmall": "/images/collection_default_s.gif",
"set": [
{
"id": "72157643471292484",
"title": "Set 1",
"description": ""
}
]
},
{
"id": "122388635-72157643469075734",
"title": "Test Gallery 1",
"description": "Bing Photos",
"iconlarge": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_l.jpg",
"iconsmall": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_s.jpg",
"set": [
{
"id": "72157643469056814",
"title": "Test Gallery 1",
"description": "Bing Backgrounds"
}
]
}
]
},
"stat": "ok"
}
So how do I pass the received data to other functions without a disruption in the data?
Code should be much like below
success: function (collections)
{
$.each(collections,function(index,item){
var i=0;
$.each(item.conllection[i],function(index,item){
alert(item.id);
i++;
});
});

JSONP Object Error

I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?
This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.

Categories

Resources