Get JSON data from WebAPI & Load data into Store - json

I am learning ExtJS-4.2, I was following their MVC tutorial...
I built my controller, view, model, store... My Store had hard-coded data. I have a working WebAPI for testing, which sends result in json format...
What the tutorial is talking about how to read from local file and send to an API,
what i want to read from API and load my data into the store...
Ext.define('AM.store.Productstore',
{
extend : 'Ext.data.Store',
model : 'AM.model.Productmodel',
autoload : true,
proxy : {
type : 'AJAX',
url : 'localhost/mfw/api/products/all'
//tutorial is no help any furthur from this point on
}
});
My URL is localhost/mfw/api/products/all
and my returning json is
[{"ID":1,"Name":"aa","Category":"A","Price":200.00},
{"ID":2,"Name":"bb","Category":"B","Price":200.00
{"ID":3,"Name":"cc","Category":"C","Price":200.00},
{"ID":4,"Name":"dd","Category":"D","Price":200.00},
{"ID":5,"Name":"ee","Category":"E","Price":200.00},
{"ID":6,"Name":"ee","Category":"F","Price":200.00}]
any help?

Please change your proxy type to 'rest' instead of 'Ajax'. More over mention your reader config. Did you map your json key with fields in model.
please refer sencha guide for more clarity.
http://docs.sencha.com/ext-js/4-2/#!/guide/data
Thanks

Here is a jsfiddle showing a grid with your data. One of the key things is the root property of the json reader. Since your data does not have a root you can leave the root property out and it should work. If you data is wrapped inside another field ie root field then specify root: 'myrootfield' in the reader. So here is your proxy. Also in your model specify the key field using idProperty in your case it is 'ID', I think extjs defaults to idProperty of 'id' lowercase so better to just specify it directly.
proxy : {
type : 'rest',
url : 'localhost/mfw/api/products/all'
reader: {
type: 'json'
}
}

Related

How to: (a) send JSON data from the browser to the controller; and (b) send the transformed data to SQL Server within ASP.NET MVC?

I have a form which includes a variety of <input> elements and makes use of 1-to-n tabulator tables for data input. I have managed to successfully assemble data from these elements into a JSON string. I am now attempting to complete the following two steps:
Using Ajax, post the JSON object to my web server; and
In the ASP.NET MVC controller, upload the deserialized JSON data into a SQL Server 2016 table.
My client-side script to POST the JSON object is as follows:
var myJson = "the data from the form elements is programmatically inserted into the JSON string";
// use parseJSON() to test the syntax
try {
var obj = jQuery.parseJSON(myJson);
}
catch(error) {
console.log(error);
}
$.ajax({
type: "POST",
url: "/Dailies/UploadJson/",
dataType: 'json',
data: JSON.stringify(myJson),
contentType: 'application/json',
crossDomain: true,
cache: false,
success: function(data) { console.log(data); }
});
The method called within my ASP.NET MVC controller appears as follows:
[HttpPost]
public IActionResult UploadJson(Object jsonFile)
{
// insert data into SQL Server table
}
Note: I have already created the appropriate domain model within my ASP.NET MVC app and have also added a DbSet reference to the DbContext model. I have verified my ability to insert rows into the SQL Server table using mock data.
When I place a breakpoint inside the UploadJson() method, I find that the jsonFile object is null.
My quandry at this point is two-fold:
I can't seem to get JSON data from the client to the web server; and
I need to better understand how to transform the JSON data (once received) for upload into my database.
Any assistance is greatly appreciated.
Although there are plenty of questions related to this, the answers to those typically refer to binding to a model instead of just the json string. But those will also help you.
It looks like there are two things:
I would change the controller to receive a string instead of an object.
You'll need to update the json data you're passing to the controller to match the parameter name of the controller. So in this case, the controller would receive a parameter named jsonFile. So in the $.ajax method you'll want update the data to something like:
data: { jsonFile: JSON.stringify(myJson) }
UPDATE:
remove the Content-Type of application/json

response with status 200: ok

I am trying to figure out how to plot data from a local '.JSON' file using angular2-highcharts example.
I followed the example in 'https://www.npmjs.com/package/angular2-highcharts' to first understand how to plot .JSON data and it worked. I took the data available for the example and created a local .JSON file (copied the content from 'https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK' in notepad and saved it with UTF-8 encoding as a .JSON file), and replaced the file path for the JSON request to this. When I do this though, I get an error - response with status 200.
constructor(jsonp : Jsonp) {
//jsonp.get('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK').subscribe(res => {
jsonp.get('./data.json').subscribe(res => {
this.options = {
title : { text : 'AAPL Stock Price' },
series : [{
name : 'AAPL',
data : res.json(),
tooltip: {
valueDecimals: 2
}
}]
};
});
}
options: Object;
};
Since I am not super familiar with json data/ Javascript or angular2 I am not sure if I am missing something very basic here. Any help is appreciated.
as far as I know, Response Status 200 specifies that request was successful. i.e. your request was successfully handled. perhaps you want to try checking response data.
check your callback for response data.
Using http instead of json helped. I made use of the suggestion in this answer https://stackoverflow.com/a/36305814/4567096.

MediaType should be application/schema+json to validate schema

I'm using justinrainbow/json-schema class to validate data against a schema.
However I'm receiving this error:
Media type application/schema+json expected
I could try to change ContentType in nginx for all my json files, but it doesn't make sense.
Another way would be to change the constant inside the library to 'application/json' (as my server is delivering for json files). Again, is not ok to change the source.
Is there a way to pass this as a parameter to justinrainbow/json-schema class?
https://github.com/justinrainbow/json-schema
I couldn't find a solution for this because there is no content-type on the web as schema+json.
Just replace in justinrainbow/json-schema/src/JsonSchema/Validator.php the SCHEMA_MEDIA_TYPE to 'application/json'.
You can also serve the file by local path, not by url.
Now the library supports "json/application" additionally, but it throws an error at other content types.
To avoid this, you can extend the default "JsonSchema\Uri\UriRetriever" and override "confirmMediaType()":
class MyUriRetriever extends JsonSchema\Uri\UriRetriever {
public function confirmMediaType($uriRetriever, $uri) {
return;
}
}
$retriever = new \MyUriRetriever();
$refResolver = new JsonSchema\SchemaStorage($retriever);
$schema = $refResolver->resolveRef($schema);
$validator = new JsonSchema\Validator(new JsonSchema\Constraints\Factory($refResolver));
$validator->check($data, $schema);
$data: json decoded response from API
$schema: url of the schema
I had the same issue many times when testing other party`s API against their schema. Often they do not send the correct "Content-Type" header for their schemas and it can take long for them to change it.
Update: Ability to exclude endpoints from validation
You can use UriRetriever:addInvalidContentTypeEndpoint():
$retriever = new UriRetriever();
$retriever->addInvalidContentTypeEndpoint('http://example.com/car/list');

EXTJS 3.4 Load JSON data into a TREE dynamically

I need to load JSON data into a Tree or TreePanel.
The JSON data does not come from a file or retrived from a URL but is built on the fly.
I cannot find any examples.
Can anyone help?
While I was trying to create a Treegrid afetr searching something in a search filed (need to pass this in the URL) i found some strange behaviour.
How I created here is the logic:
Created a Tree class with rootVisible: false and store:mystore
My store has no proxy{} as I had to set this dynamically from controller
Inside the store autoLoad:false was there
Used mystore.load() to load the data into tree
Request was going for 2 times
A blank root node in the tree although I have no root node.
I fixed it in the following way... not sure to wat extend this is correct. Any better solution please share
Tree class(View)
Didn’t define any treestore inside tree view
rootVisible: false
Inside the controller
search: function(button){
var searchText = this.getSearchField().value;
//created a store instance
var mystore = Ext.data.StoreManager.lookup('MyTreeStore');
mystore.setProxy({
type: 'ajax',
url: 'app/searchid/'+searchText;
});
var mytree = Ext.create('AM.view.MyTree',{store:mystore});
Ext.getCmp('tn').add(mytree);
//DON’T USE store.load() method As we have set rootVisible: false so it will automatically try to load the store or will send the request
}
Store file
Ext.define('AM.store.BomTreeStore', {
extend: 'Ext.data.TreeStore',
model: 'AM.model.BomTree',
autoLoad: false,
folderSort: true
});
Any better solution to this plz share :)
You can do it by progammatically creating a root node.
Iterate through your data and keep appending child nodes to your root node.
It has been explained quite well here:
ExtJS: How to create static and dynamic trees

Extjs store reader fully qualified json property names

Using Extjs 3+ and server side is sending back the following JSON:
{"com.klistret.cmdb.ci.pojo.QueryResponse": {"com.klistret.cmdb.ci.pojo.successful":true,"com.klistret.cmdb.ci.pojo.count":1,"com.klistret.cmdb.ci.pojo.elements":{"com.klistret.cmdb.ci.pojo.id":123,"com.klistret.cmdb.ci.pojo.name":"Mars","com.klistret.cmdb.ci.pojo.fromTimeStamp":"2010-07-08T16:38:00.478+02:00","com.klistret.cmdb.ci.pojo.createTimeStamp":"2010-07-08T16:38:00.478+02:00","com.klistret.cmdb.ci.pojo.updateTimeStamp":"2010-10-25T15:02:09.446+02:00","com.klistret.cmdb.ci.pojo.type":{"com.klistret.cmdb.ci.pojo.id":1,"com.klistret.cmdb.ci.pojo.name":"{http:\/\/www.klistret.com\/cmdb\/ci\/element\/logical\/collection}Environment","com.klistret.cmdb.ci.pojo.fromTimeStamp":"2009-08-05T11:20:12.471+02:00","com.klistret.cmdb.ci.pojo.createTimeStamp":"2009-08-05T11:20:12.471+02:00","com.klistret.cmdb.ci.pojo.updateTimeStamp":"2009-08-05T11:20:12.471+02:00"},"com.klistret.cmdb.ci.pojo.configuration":{"#www.w3.org.2001.XMLSchema-instance.type":"com.klistret.cmdb.ci.element.logical.collection:Environment","#Watermark":"past","com.klistret.cmdb.ci.commons.Name":"Mars"}}}}
The reader is setup up as follows:
var reader = new CMDB.JsonReader(
{
totalProperty : 'com.klistret.cmdb.ci.pojo.count',
successProperty : 'com.klistret.cmdb.ci.pojo.successful',
idProperty : 'com.klistret.cmdb.ci.pojo.id',
root : 'com.klistret.cmdb.ci.pojo.elements'
},
[
{name: 'Id', mapping: 'com.klistret.cmdb.ci.pojo.id'},
{name: 'Name', mapping: 'com.klistret.cmdb.ci.pojo.name'}
]
);
The store as:
var ds = new Ext.data.Store({
proxy : new Ext.data.ScriptTagProxy({
url : 'http://sadbmatrix2:55167/CMDB/resteasy/element'
}),
reader : reader
});
The reader extends the Ext.data.JsonReader as explained by http://erichauser.net/2007/11/07/more-wcf-json-and-extjs/ to remove the "com.klistret.cmdb.ci.pojo.QueryResponse" start node in the JSON returned from the server.
The extended reader never gets called. Assuming the problem is due to has fully qualified property names in the JSON object returned (ie. "com.klistret.cmdb.ci.pojo.name" rather than just "name").
Anybody use gotten around this?
We worked it out (well, mostly Matthew did) in the comments:
ScriptTagProxy needs the server to wrap the JSON data in a function call so that your local code can get access to it.
Instead of the server emitting something like:
{here:'is data}
it needs to return
somefunc("{here:'is data'}");
That way, your client-side implementaiton of somefunc() is called and can process the returned data.