How to get Model attributes from nested json object in Backbone - javascript

** JSON Data **
{
"data" : [{
"book" : "first book", -- > i want this via model.get('book');
"aurthor" : "xyz"
}
]
}
** Get json data using jquery Ajax. **
var jsonData = {};
$.ajax({
url : 'booklist.json',
async : false,
dataType : 'json',
success : function (json) {
jsonData = json.data;
}
});
** Model declaration here **
var MyModels = Backbone.Model.extend({
initialize : function () {},
defaults : {}
});
var modelinstance = new MyModels(jsonData);
modelinstance.get('book'); // it is giving undefined how can i get this value.
** Please help where i doing wrong.i am new in Backbone. **

If the data is always a single object wrapped up like that then you'd just add a parse method to your mode:
parse model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
Something like this:
parse: function(response) {
return response.data[0];
}
You can also trigger a parse call through the model constructor using the parse: true option:
constructor / initialize new Model([attributes], [options])
[...]
If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the model.
So if you're manually loading the data through a $.ajax call then you'd have something like this:
success: function (json) {
var m = new MyModel(json, { parse: true });
// Do something with m...
}

Related

jquery- can not retrieve data from object type response which I get through ajax call

I have a page for a table. I am trying to get data from api by ajax call and retrieve that data and trying to show it in the table of the page.
So , I need key and value both. I want to set key as a column name ( header for column ) and value for row.
But I can't retrieve my data from the response and can not bind it in the html page.
Here is my Controller:
public ResponseEntity<Object> findPaginated(
#RequestParam("page") int page, #RequestParam("size") int size) throws NotFoundException {
JsonParser parser = new BasicJsonParser();
HttpHeaders headers = new HttpHeaders();
ApiResponse response = new ApiResponse(false);
Page<EmployeeDesignation> resultPage = designationService.findPaginated(page, size);
List<EmployeeDesignation> parseList = resultPage.getContent();
response.setSuccess(parser.parseList(String.valueOf(parseList)));
headers.add("totalelement", String.valueOf(resultPage.getTotalElements()));
headers.add("totalpages", String.valueOf(resultPage.getTotalPages()));
System.err.println ( " in controller ");
return ResponseEntity.ok()
.headers(headers)
.body(response);
}
This is my ajax call format ( .js file ) :
function getList() {
$http({
url: "/api/designation/designations/get?",
method: 'GET',
params:{ page: 2, size: 2 }
}).then(function successCallback(response) {
let info = Object.values(response.data.data);
let check = Object.values(info);
console.log("keys::::" + check);
getArray(check);
}
, function errorCallback(data) { });};
function getArray($products){
jQuery($products).each(function(i, obj) {
jQuery('div#check').append(obj.name + '::::::contains ::::::' +obj.designationRefId);
});
}
But when I append the data on page , it shows undefined.
Here is my .json format file :
{
"success": true,
"message": null,
"data": [
"EmployeeDesignation{id=75928ab9-7c97-442d-b777-dc32ca9ef49d, version=0, refId=0, designationRefCode='2', name='programmer'}",
"EmployeeDesignation{id=57305c1f-bca0-4a56-ba19-5784c4461f5b, version=0, refId=0, designationRefCode='2', name='designer'}"
]
}
This the output of of: console.log( JSON.stringyfy(response)):
{"data":{"success":true,"message":null,"data":["EmployeeDesignation{id=75928ab9-7c97-442d-b777-dc32ca9ef49d, version=0, refId=0, designationRefCode='2', name='programmer'}","EmployeeDesignation{id=57305c1f-bca0-4a56-ba19-5784c4461f5b, version=0, refId=0, designationRefCode='2', name='designer'}"]},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/designation/designations/get?","params":{"page":2,"size":2},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"complete"}
How can I solve this matter? How can I bind these data on table ???
It seems converting the list into string is generating this format.
You can try any of the two,
During showing the data remove the "EmployeeDesignation" from each array element.
Or,
Make the JSON Object of your own without converting to String.

Initialize Model elements in javascript/backbone

I am getting a nested JSON data from REST. Now I want to capture that value in a variable. Everything is working fine but I don't know how should I initialize that variable.
So here is my initialize method of Model.
initialize: function() {
var self = this;
if (!this.get('dropdownData')) {
this.set({
dropdownData: []
});
}
}
}
AJAX CALL:
fetchDropdown: function(data) {
var self = this;
var d = $.Deferred();
var dropdownRequest = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: this.urlRoot,
data: JSON.stringify(data)
});
dropdownRequest.done(function(data)
{
self.set({
dropdownData: data
});
console.log("JSON SUCCESS!! YAY!!");
d.resolve();
});
Now dropdownData should be initialized as dropdownData: {} or dropdownData: [] or I don't need to initialize it at all.
P.S: Logic wise code snippet is working. I just want to know what's the correct way to initialize the dropdownData in the initializefunction in BACKBONE MODEL
I would recommend avoiding initializing dropdownData in the initialize method entirely, instead utilizing model.defaults here. If you add the following to your model definition:
defaults: function () {
return {
dropdownData: []
};
},
...then you can remove all the code in the body of your initialize method. The result of this change will be that an instantiated model will either have the supplied value (at instantiation) for dropdownData or the model will default to the empty array specified.
Note that it's important to use the function version of defaults here. If you were to do this instead:
defaults: {
dropdownData: []
},
...then any instantiated model not supplied with a value for dropdownData would share a value for dropdownData. Every instance would refer to the exact same array.

Proper technique to pass javascript array to controller with List<int> parameter

I have a controller that takes a List<int> and I am calling from AJAX. The controller is hit, but the parameter is always null.
My controller:
public ActionResult MinorAreas(List<int> majorareas)
{
// ...
}
jQuery call:
function onChange(e)
{
var cur = this.value(); // an array of numbers like [2,4,7,9]
$.ajax({
cache: false,
type: "GET",
traditional: true,
url: "#(Url.RouteUrl("GetMinorAreas"))",
data: { "majorareas": cur},
success: function (data) {...},
error: function (xhr, ajaxOptions, thrownError) {... }
});
}
Route definition:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
new[] { "ABC.ZZZ.Controllers" }
);
Using fiddler, I can see that the URI is built correctly:
# With an array of [2]
http://localhost:15536/minorAreas?majorareas=2&_=1450307693166
# With an array of [2,3,9]
http://localhost:15536/minorAreas?majorareas=2&majorareas=3&majorareas=9&_=1450308261808
I've already looked at this question about passing arrays to a controller with a List<int> parameter, but the solution doesn't seem to work for me. What am I doing wrong?
It looks like the network request is being generated correctly. The problem is in the route definition:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
new[] { "ABC.ZZZ.Controllers" }
);
majorareas=new List<int>() is going to ensure that majorareas is always an empty list, even when it otherwise would be populated!
You don't have to define parameters here; the method definition in the controller does that. Leave it off, and it should work fine:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas" },
new[] { "ABC.ZZZ.Controllers" }
);

backbone success event not called

Code
MyClass = Backbone.Model.extend({
url: '/apiurl/'+sessionValue+'',
defaults: {
data1: '',
data2: 1
}
});
var myobj = new MyClass ();
var myobjvalue = {
data1: "myvalue"
};
myobj.save(myobjvalue , {
success: function (myobj , response) {
alert("success");
},
error : function (myobj , response) {
var data = JSON.stringify(response);
console.log(data);
}
})
in the above code, save function successfully calls the REST api. (200 OK). However even after that it enters in error block.
value printed in console
{"readyState":4,"responseText":"Success","status":200,"statusText":"OK"}
What should I be doing?
===================================
What worked
Instead of string, I had to return actual object as part of REST API. apprently, backbone expects class object along with HTTP status. so responseText contained full myobj.
What worked
Instead of string, I had to return actual object as part of REST API. apprently, backbone expects class object along with HTTP status. so responseText contained full myobj.

How to send data to controller by using YAHOO connect and json

I can not send data to MVC controller using YAHOO connect library.
Parameters query and filter are NULL. Where is the problem?
// --- JavaScript --- //
var callbacks = {
// Successful XHR response handler
success: function (o) {
var messages = [];
// Use the JSON Utility to parse the data returned from the server
try {
messages = YAHOO.lang.JSON.parse(o.responseText);
}
catch (x) {
alert("JSON Parse failed!");
return;
}
handleSearchResult(messages, query, filter);
},
argument: { query: "flowers", filter: "home" }
};
// Make the call to the server for JSON data
YAHOO.util.Connect.asyncRequest("GET", "Search/GetTopics", callbacks);
// --- C# --- //
//Controller
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTopics(string query, string filter)
{
// query and filter are NULL <- problem here //
// ...do my stuff... //
return Json(Search(query, filter), JsonRequestBehavior.AllowGet);
}
Thank you! :)
You have to possibilities to send parameters:
Use GET verb: In this case you need to pass the parameters in the querystring:
YAHOO.util.Connect.asyncRequest('GET',
'Search/GetTopics?query=foo&filter=bar', callbacks);
Use POST verb: In this case you could use the postData parameter
YAHOO.util.Connect.asyncRequest('POST', 'Search/GetTopics',
callbacks, 'query=foo&filter=bar');
In the first case it is actually recommended to use Url helpers to generate the address to make sure values are properly url encoded:
var url = '<%= Url.Action("GetTopics", "Search", new { query = "foo", filter = "bar" }) %>';
YAHOO.util.Connect.asyncRequest('GET', url, callbacks);
The same is true for the second case. Make sure to properly encode values.

Categories