AJAX response: sugestions for JSON format? - javascript

Say I submit a form via Ajax and need a response from the server:
Pass/fail indicator
On fail, a list of validation errors with associated field ids/names, etc
Is there a standard or best practice for the JSON format for such a structure? If so, I'd like to try to stick to it instead of coming up with my own convention.

OmniTI has a decent standard that I like and recommend: http://labs.omniti.com/labs/jsend
{
status : "success",
data : {
"posts" : [
{ "id" : 1, "title" : "A blog post", "body" : "Some useful content" },
{ "id" : 2, "title" : "Another blog post", "body" : "More content" },
]
}
}
I usually use a variant:
{
status : "error",
messages : {
"some_field" : "message"
}
}

Peter Bui's got this proposal format: http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery
{
status: "ok|redirect|error",
to: "http://www.redirect-url.com",
html: "<b>Insert html</b>",
message: "Insert some message here"
}

{
"result": "false",
"fields":
[
{"id": "element1", "name": "element1"},
{"id": "element2", "name": "element2"},
{"id": "element3", "name": "element3"}
]
}

Hmm. I don't know about a standard, but you might want to just do something like
{
"result": "false",
"errors":
[
{"errorCode": "1234", "errorText": "malformed address"},
{"errorCode": "5678", "errorText": "no username"}
]
}

Related

Parse nested JSON Response Javascript

I know there are several threads on this subject but I've looked through over 30 threads without success.
I have managed to parse a JSON response so it looks like this:
{
"1": {
"id": "1",
"name": "Fruit",
.
.
.
"entities": {
"1": {
"id": "1",
"name": "blue bird",
.
.
.
"status": "1"
},
"2": {
using this code
let json = JSON.parse(body);
console.log(json);
Now I want to access the "id", "name" etc. AND the "id" and "name" for the "entities" tag.
So far I have tried:
console.log(json[0]);
console.log(json.id);
which both returns undefined
I have also tried
console.log(json[0].id);
which gives an error
Any ideas?
In this instance, your first key is 1, so you can access it with json[1].
const json = {
"1": {
"id": "1",
"name": "Fruit"
},
"2": {
"id": "2",
"name": "Veggies"
}
};
console.log(json[1]);
In this json, you can reach the id by
json.1.id
But I think that first of all your json is not correctly written, you should have something like
{
"elements": [
{ "id" : 1, "name" : "fruit" },
{ "id" : 2, "name" : "vegetable" }
]
}
like that, json.elements is a collection/array, and you can loop, count, or any other things you will not be able to do because your json looks like a super heavy list of different properties ( he doesn't know that json.1 and json.2 are the same type of objects.
const jsonData = JSON.parse(body);
for (const i in jsonData) {
for (const j in jsonData[i]) {
console.log('${i}: ${jsonData[i][j]}');
}
}

Rebuilding JSON for JSTree

It's my first meeting with JS so i have some troubles with understanding what I need to do.
I have my own REST service. I get JSON from it.
JSON looks like
{"list": [
{
"id_depart": 1,
"id_parent_depart": 1,
"address": "Pobeda 30",
"name_depart": "ParentDepartment",
"name_parent_depart": "ParentDepartment"
},
{
"id_depart": 101,
"id_parent_depart": 1,
"address": "gjh",
"name_depart": "xxbxgh",
"name_parent_depart": "ParentDepartment"
},
{
"id_depart": 201,
"id_parent_depart": 1,
"address": "some addr",
"name_depart": "department1",
"name_parent_depart": "ParentDepartment"
},
{
"id_depart": 203,
"id_parent_depart": 1,
"address": "some addr",
"name_depart": "department2",
"name_parent_depart": "ParentDepartment"
},
{
"id_depart": 202,
"id_parent_depart": 201,
"address": "some addr",
"name_depart": "sub-department!",
"name_parent_depart": "department1"
}]}
There are an entries which have some another entries inside. It managed by "parent id's".
So there i want to create JSTree which displays this interaction.
After some hours of reading JSTree docs i understand that it use specific json format for build a tree. But I have no idea how convert my json to needed.
Also in result tree i nees to make POST requests onClick on nodes, so I need to store objects from my REST json into maybe metadata of treeObjects.
So, please, if someone can give me a little advice, it will be great! Thank you!
There a code from JSTree example
$(function () {
$("#demo1").jstree({
"json_data" : {
"data" : [
{
"data" : "A node",
"metadata" : { id : 23 },
"children" : [ "Child 1", "A Child 2" ]
},
{
"attr" : { "id" : "li.node.id1" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
}
]
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) { alert(jQuery.data(data.rslt.obj[0], "id")); });});

Get a specific element from JSON

I know this is a very simple and common question; I've already read some Q/A but I can't figure out how to solve my problem.
I have this short json from an AJAX call that execute a SPARQL query:
{
"head": {
"vars": [ "name" , "email" ]
} ,
"results": {
"bindings": [
{
"name": { "type": "literal" , "value": "Name Surname" } ,
"email": { "type": "literal" , "value": "name.surname#email.com" }
}
]
}
}
I'm searching name and email of a single user of the application, so
the result should be always made up of a single element.
What I want to retrieve is the "name" of the user.
I tried something like:
response["name"].value
//or
response[0]["name"]
//or
response.name
but always wrong.
How can I get the name value? Thanks to everyone who will help.
Try this
response.results.bindings[0].name.value
response.results.bindings[0].email.value
Update
Example
You can check out the fiddle created here
http://jsfiddle.net/uqxp4j73/
The code for this is as under
var x='{ "head": { "vars": [ "name" , "email" ] } , "results": { "bindings": [ { "name": { "type": "literal" , "value": "aadil keshwani" } , "email": { "type": "literal" , "value": "name.surname#email.com" } } ] }}';
obj = JSON && JSON.parse(x) || $.parseJSON(x);
console.log(obj);
console.log(obj["results"]["bindings"][0]["name"]["value"]);
alert(obj["results"]["bindings"][0]["name"]["value"]);
Hope this helps :)
In JSON, you always have to provide the full path to the property you like to reach. Assuming you have stored the parsed JSON in variable response, the following paths will get you corresponding value.
response.results.bindings[0].name.value for name
response.results.bindings[0].email.value for email
Recommend you to go through http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ to get basic concepts of JSON.

Correct way to write ColdFusion service to send json data and catch by angularjs

I'm Very stuck in this case when working all day :(. please help me.
I have website need using $http provider to call ColdFusion file from other domain.
let's say this is link to cfm file : http://xample.com/getStockCodesTest.cfm
this is may sample ColdFusion file:
<cfcontent
type="application/json"
/>
{
"items": [
{
"StockCode" : { "col": "Stock Code", "value": "0231" },
"Qty" : { "col": "Qty", "value": "DS" },
"QtyOn" : { "col": "Qty On", "value": "Branch" },
"QtyVal" : { "col": "Qty Val", "value": "200" },
"ReleasedDate" : { "col": "Released Date", "value": "0" },
"S" : { "col": "S", "value": "0" },
"Description" : { "col": "Description", "value": "adfasdf" },
}
]
}
this is angular code (i use coffeescript to write)
ajax = $http {
url: 'http://xample.com/getStockCodesTest.cfm'
method: 'JSONP'
params: {
callback: "JSON_CALLBACK"
}
}
ajax.success (data, status, headers, config) ->
console.log data
but when check firebug. it always return error:
so how can i have a correct way to write a test ColdFusion with content json like that and use angularjs to catch in to my web :(
I'm not exactly sure what you are asking. But I can tell you that you are getting the error because you have invalid JSON.
That comma, right there, remove it. It makes for invalid JSON.
You have to wrap your JSON with the input function name, when a JSONP call is made from AngularJS. That is the reason you see the error.
Example of JSONP response:
/xxx.cfm?_jsonp=angular.callbacks._0 --- request
//expected response is like this - a function from your coldfusion
angular.callbacks._0([{"StockCode" : { "col":...
Then it will work.

jQuery inserting JSON value to element with specific class

I'm have a little trouble with some jQuery I have been trying to put together today.
Basically what I am trying to achieve is to dynamically have prices inserted into a price button on my page by reading from a JSON feed.
The idea is that there is an empty span that will contain the price. I have given all of the price spans the class .getPriceNew. Each span also has an id which is equal to the SKU number for the item like this <span class="getPriceNew" id="123456"></span>.
The mechanic is that for each span that has the class .getPriceNew the JSON will be queried for the information with the SKU id used as part of the query string.
Here is an example of the code i have tried
jQuery
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
HTML
<span class="getPriceNew" id="123456"></span>
<span class="getPriceNew" id="789123"></span>
<span class="getPriceNew" id="456789"></span>
<span class="getPriceNew" id="654321"></span>
JSON Example
This is what a single item from the JSON feed would look like - I have filtered it a little
/api/MyApi.svc/GetProductBySku/123456
Updated with valid JSON
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://someurl.com/productImages/assets/img//icon18.gif"
},
"Barcode": {
"Barcode": "5026555408684"
},
"Description": "HTML",
"Id": 12214,
"Packshots": [
"http://someurl.com/productImages/914383/1min.jpg",
"http://someurl.com/productImages/914383/2med.jpg",
"http://someurl.com/productImages/914383/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Format",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Product Title",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Take Two Interactive Software"
},
"VideoHTML": "HTML",
"status": {
"Response": "product found",
"Success": true
}
}
I would love some help on this as I am really scratching my newbie head at this stage. I have managed to have console.log output the prices to the log but when I try and insert them back into the spans all I get is [object] [Object].
You are doing
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
getJSON returns a jqXHR object, which is not what you need. Try this:
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
// Save a refference to this span.
var thisSpan = $(this);
$.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
// Request complete, NOW we can use the data we got!
thisSpan.html("€"+data.Variants[0].Price);
});
})
The callback is where you want to use the data you get from your AJAX calls. All AJAX methods ($.ajax, $.get, $.post, $.getJSON, etc) will return a jqXHR object.
I think your javascript code is correct but your Json output has two errors:
1: "Description":"Some HTML Description here, <- you forgot the closing quote
2: "ID":0}, <- delete the closing brace
So your Json will result like this:
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://url.com/image.gif"
},
"Barcode": {
"Barcode": "4876416541647"
},
"Description": "Some HTML Description here",
"Id": 12214,
"Packshots": [
"http: //url.com/productImages/914383/1min.jpg",
"http: //http: //url.com/2med.jpg",
"http: //http: //url.com/3max.jpg"
],
"ID": 0,
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Titleoftheproduct",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Vendorname"
},
"VideoHTML": "<iframewidth="725"height="408"src="http: //www.youtube.com/embed/videoseries?list=PLofwA47XDv2_KnfUY52_8mlWg0iUEv8ci"frameborder="0"allowfullscreen></iframe>",
"status": {
"Response": "productfound",
"Success": true
} }
now your code
data.Variants[0].Price
will return 49.97
to validate Json you can paste it into http://jsonlint.com/ i think is very useful
Hope this helps

Categories

Resources