How to query JSON file in emberjs - ember.js

I´ve never work with JSON before, but have with xml, php, mysql. I have a populated database on the server and would like to develop a web application with ember.js to interact with this data (CRUD).
Where should I start? I know ember-data has most of the things I would need when developing, but I'm unsure of how to start.
Since the database holds different tables, is it possible to keep this information in one json file? is it the appropriate way to do it? How do I automatically produce this json file from the server?

you can start with a read query :
You upload a file sample with the json syntaxe on your server (or use your json service if it's enable) to start quickly. Test that you can access to it in your browser, for example :
[ {"id": 1, "desc": "hmarchadour"}, {"id": 2, "desc": "moderator"} ]
Well now you take/create a view in your embjer js and you can use JQuery to call this file/service :
Ember.View.create({
templateName : "templateName" // you
stuff : [],
didInsertElement : function() {
$.ajax({
type : "GET",
url : <url-of-your-sample>,
dataType: "json",
success : function(result) {
var tmpStuff = json2Stuff(result);
this.set('stuff', tmpStuff);
},
error : ... }
);
}
});
Regards,

Related

Ember-models-table addon throws ember warn error while trying to use 'routeName' property

Am using ember-models-table to display table in my applicaiton. The table is great for sorting , pagination etc, but am trying to route from specific row to different page based on the id. it has mentioned in its example to use 'routeName'
But when I use it throws the following error:
"Assertion Failed: When calling warn you must provide an options hash as the third parameter. options should include an id property."
My .js coding :
columns:[
{
"propertyName": "firstName",
"title":"First Name",
"routeName":"/#/profile/_id"
},
and so on
Thanks for your help.
update: the error is gone after updating ember to ember 3.1.2
but there is a warning and its not functioning properly as expected , where am i going wrong?
my code :
columns:[
{
"propertyName": "firstName",
"title":"First Name",
"routeName":"profile"
},
If you look at the example app for this addon, you'll see the following syntax for the route:
{
propertyName: 'id',
routeName: 'users.user'
},
This roughly corresponds to a route like users/1. So, if this is your router:
Router.map(function() {
this.route('users', function() {
this.route('user', { path: '/users/:user_id' });
});
});
And here are the columns:
columns: [
{
"propertyName": "something",
"routeName": "users.user"
},
{
"propertyName": "id",
"routeName": "users.user"
}
]
Here's the template:
{{models-table
data=model
columns=columns
...
}}
routeName should not include the id segment.
Hover over the anchor tag created to see where it leads to, and make adjustments until it matches where it should go. It will only render when there's a valid route for the link. The path seems like it might be relative, so if you're already on the users route, you may only need to specify user for the routeName.
I figured this out by searching the addon codebase for routeName and then trying it out with the same kind of format that {{link-to}} helper uses in Ember.
P.S. this is some missing info in the documentation, so if this addon is helping you out, consider making a PR to help others.

Loading a single record with Ember 2.0 and Ember Data 2.0

I've come unstuck when trying to fetch a single record using Ember Data 2.
The server is designed to respond to a GET request like this:
GET http://server/api/results/1
with this as a result:
{
"results" : [
{
"id": 1,
"catname": "Category 1",
}
]
}
The Ember route code looks like this:
export default Ember.Route.extend({
model: function() {
return this.store.find('game',12);
}
});
The problem is that there doesn't appear to be a network request going out (a previous findAll fetch has worked, so I don't think it's the adapter), and there is an error I have not been able to find informaiton on:
Uncaught TypeError: Cannot set property'crossDomain' of undefined
Does anyone have any idea what this could be, of hint at how I might track this down?
In 1.13 new methods was introduced. You should use findRecord instead of find.
Also, ember expects following response when fetching a single object:
{
"result" :
{
"id": 1,
"catname": "Category 1",
}
}

How to Model.fetch(<object>) when the returned data is a single object

I want to make an API call for searching that looks like this:
https://myapi.com/search/<query>/<token>
where query is the search term and token (optional) is an alphanumeric set of characters which identifies the position of my latest batch of results, which is used for infinite scrolling.
This call returns the following JSON response:
{
"meta": { ... },
"results" {
"token": "125fwegg3t32",
"content": [
{
"id": "125125122778",
"text": "Lorem ipsum...",
...
},
{
"id": "125125122778",
"text": "Dolor sit amet...",
...
},
...
]
}
}
content is an array of (embedded) items that I'm displaying as search results. My models look like this:
App.Content = Em.Model.extend({
id: Em.attr(),
text: Em.attr(),
...
});
App.Results = Em.Model.extend({
token: Em.attr(),
content: Em.hasMany('App.Content', {
key: 'content',
embedded: true
})
});
In order to make that API call, I figured I have to do something like this:
App.Results.reopenClass({
adapter: Em.RESTAdapter.create({
findQuery: function(klass, records, params) {
var self = this,
url = this.buildURL(klass) + '/' + params.query;
if (params.token) {
url += '/' + params.token;
}
return this.ajax(url).then(function(data) {
self.didFindQuery(klass, records, params, data);
return records;
});
}
}),
url: 'https://myapi.com/search',
});
then somewhere in my routes do this:
App.Results.fetch({query: 'query', token: '12kgkj398512j'}).then(function(data) {
// do something
return data;
})
but because the API returns a single object and Em.RESTAdapter.findQuery expects an array, an error occurs when Ember Model tries to materialize the data. So how do I do this properly? I'm using the latest build of Ember Model.
By the way, I'm aware that it would be much more convenient if the API was designed in a way so I can just call App.Content.fetch(<object>), which would return a similar JSON response, but I would then be able to set the collectionKey option to content and my data would be properly materialized.
You simply need to override your models load() method to adjust the payload hash to what Ember.Model wants. There are no serializers in Ember.Model. There is both a class level load for handling collections and an instance level load for loading the JSON specific to a single model. You want to override the instance level load method to wrap the content key value in an array if its not one already.
I have been using Ember.Mode quite heavily and enhanced it for a number of my use cases and submitted PR's for both fixes and enhancements. Those PRs have been sitting there for a while with no response from the maintainers. I have now moved to Ember.Data which has been 'rebooted' so to speak and having a lot better result with it now.
I would strongly suggest walking away from Ember.Model as it appears dead with the new pragmatic direction Ember Data has taken and because the project maintainer doesn't appear to have any interest in it anymore.

Ember.JS: Your server returned a hash with the key id but you have no mapping for it

Consider this Ember JS Model:
App.User = DS.Model.extend({
firstName: DS.attr('string')
});
I am able to successfully save the model on the server using this as an XHR request:
{
"user": {
"first_name":"dude"
}
}
but for some reason it gives me an error while returning this XHR response:
{
"id":1,
"user":{
"first_name":"dude"
},
"createdAt":"2013-04-12T03:13:52.382Z",
"updatedAt":"2013-04-12T03:13:52.382Z"
}
The error says: Your server returned a hash with the key id but you have no mapping for it
Ember expects the output to look like:
{
"user": {
"id":1,
"first_name":"dude",
"createdAt":"2013-04-12T03:13:52.382Z",
"updatedAt":"2013-04-12T03:13:52.382Z"
}
}
I think the problem lies in the request itself, but I'm not sure.
Note that I'm using the Sails API as my backend.
You can use a controller to marshal the data format to whatever you need-- but this raises an interesting question about adding support for different front-end conventions to the API blueprints. Right now, Sails.js API blueprints support Backbone out of the box, but obviously that doesn't do you a lot of good if you're using Ember :) I created an issue for that here https://github.com/balderdashy/sails/issues/317.
Here's a hacky example of how you'd use a custom controller to send back data in this format using Sails today:
// api/controllers/UserController.js
module.exports = {
// Create action: (e.g. using default route, you'd POST to /user/create)
create: function (req,res) {
// Grab attributes from request using Ember conventions
var newAttributes = req.param('user');
// Create the user object in the datastore
User.create(newAttributes, function (err, newUser) {
// If there was an error, handle it
if (err) return res.send(err,500);
// Respond with the user object using Ember conventions
res.json({
user: newUser
});
});
}
};
That's a weirdly formatted JSON response. Do you have access to the server?
Ember expects the response as a a hash with root keys
{
"user": {
"id":1,
"first_name":"dude",
"createdAt":"2013-04-12T03:13:52.382Z",
"updatedAt":"2013-04-12T03:13:52.382Z"
}
}

Getting callback is undefined error in firebug console while creating a datasource using kendo ui

My webservice generates jsonp response same as http://demos.kendoui.com/service/products.
When i try to create datasource for my webservice i am getting callback is not defined error in firebug console.
Webservice response.
callback([{"category":null,"productName":"Puma","productId":1,"quantity":0,"price":3000.0,"categoryId":1,"description":"ok"}])
But when i use kendo ui webservice (http://demos.kendoui.com/service/Products) i am getting a valid datasource.
Code :
$(document).ready(function() {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
//url: "http://demos.kendoui.com/service/products",
url: "http://localhost:8080/mobile-services/rest/categories/1/products.json",
dataType: "jsonp"
}
},
pageSize: 12
});
$("#pager").kendoPager({
dataSource: dataSource
});
$("#listView").kendoListView({
dataSource: dataSource,
template: kendo.template($("#template").html())
});
});
please suggest.
I guess the function name is not callback callback is just the key and the function itself maybe called sth like jQuery17101014779508113 Can you look at what your datasource is sending to the server during the read operation? (Chrome / Firebug Network Tab) I'm taking the $_REQUEST['callback'] variable (with a PHP-Script) and just returning it as the padding. Since you're just using a static .json file and the callback function name will be changed on each request (to prevent caching), you won't ever have the correct function name.
So: I suggest you use JSON instead of P or you dynamically return the same callback you're receiving.
Cheers....
You have specified JSONP as dataType and you are requesting a JSON file. JSONP and JSON are not the same. Try using dataType: "json".