Not all attributes of JavaScript object being mapped into JSON - javascript

I'm using Inkfilepicker.io for picture uploading on a project I'm working on. When you upload a picture, it returns a JavaScript object with some data in it. I need more, though. So I query their API using their SDK to get more. I then add this information to each object. Lastly, I post these objects using jQuery to process it on the backend. However, none of the second batch of information goes along for the ride on the backend. I manually used JSON.stringify() to see what the data looked like before it was posted. The new data was not included.
fp.pickAndStore({multiple: true}, {}, function (InkBlobs)
{
InkBlobs = $.map(InkBlobs, function(blobio, index)
{
fp.stat(blobio, {
width: true,
height: true
}, function(meta) {
blobio.width = meta.width;
blobio.height = meta.height;
});
return blobio;
});
console.log(InkBlobs);
console.log(JSON.stringify(InkBlobs));
$.post('/picture', { blobs: InkBlobs }, function(data)
{
console.log(data);
}, 'json');
});
How can I make sure all of the attributes get sent?
UPDATE
The string created by the JSON.stringify() looks like the following:
[{"url":"https://www.filepicker.io/api/file/PinzEEUlRhSCpc4dYa0w","filename":"browserWars.jpeg","mimetype":"image/jpeg","size":34284,"key":"Vx1xEuqHTKKCM4hjR6LL_browserWars.jpeg","container":"kandidlypictures","isWriteable":true},{"url":"https://www.filepicker.io/api/file/wdnWcCUWStiBxbrONeSN","filename":"1440-music-is-the-food.jpg","mimetype":"image/jpeg","size":97814,"key":"0RrSFSQBTCiifZ8ZkuIj_1440-music-is-the-food.jpg","container":"kandidlypictures","isWriteable":true},{"url":"https://www.filepicker.io/api/file/trdKhlORPCJEu3JRbPYf","filename":"any_browser.jpeg","mimetype":"image/jpeg","size":271194,"key":"1aJNE9MSEyEiAJZAacfD_any_browser.jpeg","container":"kandidlypictures","isWriteable":true}]
The expected output should also include a width and height for each object.

Use a separate named function:
var data = {
width: true,
height: true
};
var fn = function fn(meta)
{
blobio.width = meta.width;
blobio.height = meta.height;
$.post('/picture', { blobs: InkBlobs }, function(data)
{
console.log(data);
}, 'json');
};
fp.statSync(blobio, data, fn)
Or use statSync since stat is asynchronous:
fp.statSync(blobio, {
width: true,
height: true
}, function(meta) {
blobio.width = meta.width;
blobio.height = meta.height;
});
References
Fun with Named Functions
statSync

Related

AngularJS Read From JSON Returning Nothing

I am building an application that has a button that loads up help based on IDs from the JSON, when I have the JSON in the controller.js I see it on the web page but if I do it externally I do not see anything. I feel I am missing something extremely simple but may be over looking it. Any ideas?
controllerNEW.js
app.factory("UserService", function($rootScope, $http){
function getFile(){
return $http.get('stat.json').then(function(data) {
return data;
});
}
return{statErr: getFile,
//hide the displayed tooltip based on its id
hideTooltip: function(key, scopes, data)
{
controllerOLD.js
app.factory("UserService", function($rootScope){
return{
statErr: [
{
selector: "#userEmail",
fieldTitle: "Email",
placement: "right",
content: "test",
offsetTop: 500,
correctKey: "#test",
inErrorList: false
},
{
selector: "#userId",
fieldId: "id1",
fieldTitle: "ID",
placement: "right",
content: " number should contain 4 zeroes '...0000...'",
offsetTop: 500,
correctKey: "0000",
inErrorList: false
}
],
//hide the displayed tooltip based on its id
hideTooltip: function(key, scopes, data)
{
The issue is getFile() returns a promise not the data itself. It is true that you have a .then(function(data) {return data; });, but, .then() also returns a promise.
So to fix this issue, in your actual code, after you call getFile() you also need to add .then() to have access to your data:
getFile().then(function(data){
// now you have access to your data
})
you need to access the data object in the response object.
example:
var jsonResponse = $http.get('content.json').then(function(response) {
return response.data;
});
In your example, data is the whole response to your request, including headers and status. To see your data from the 'stat.json' file, you would access the data object of your data. So, the change is.
function getFile(){
return $http.get('stat.json').then(function(data) {
return data.data;
});
}
you can try something like this
$http.get('stat.json').then(function(result){
$scope.dataset = result.data
console.log($scope.dataset)
},function(error){
console.log(error)
})

Fail to load response data jquery.easy-autocomplete.min.js:10 WARNING:

I am using the easyautocomplete, http://easyautocomplete.com/, to populate a list as the user types in a search field. The code is as follows:
var options = {
url: function(phrase) {
if (phrase !== "") {
return "http://<url>/todo?query=" + phrase + "&format=json";
} else {
return "http://<url>/todo?query=empty&format=json";
}
},
getValue: "results",
ajaxSettings: {
dataType: "jsonp"
},
requestDelay: 300,
theme: "round"
};
$("#product-list").easyAutocomplete(options);
I am getting a response from my API that looks like:
{
"results": [
"list_item_1",
"list_item_2",
"list_item_3",
...
"list_item_50"
]
}
I have a feeling I'm not formatting the response properly, but I'm not sure how to fix it.
A look through the guide it looks like getValue would be if you had an array of objects and wanted to pull a particular key from each one. From the list location section it looks like you are looking for listLocation to specify the object key that has the array of things to autocomplete. So changing getValue to listLocation should give you the results you are looking for

Kendo UI Grid Javascript datasource call to controller action

I'm having trouble binding my JavaScript kendo ui grid to model data from an action method. All the examples i see are mostly MVC wrappers and the JavaScript examples are all different and none seem to work for me.
Here is where i'm at below.
I did a generic test with static data that works.
var dataSource_Test = new kendo.data.DataSource({
data: [{ LeagueDetailGroupId: "15", GroupName: "Best Team 5"}]
});
Here is the datasource object im trying to create with the controller action:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("LeagueDetailGroup_Read", "Configuration")?_leagueTypeId=" + leagueTypeId,
// i have tried all kinds of variants here, and not sure what to put
// my action method is returning json using kendo's DataSourceResult method
//contentType: "application/json",
type: "POST"
//dataType: "odata"
},
schema: {
data: "Data", // seen this in examples, dunno what it does
total: "Total", // seen this in examples, dunno what it does
model: {
id: "LeagueDetailGroupId",
fields: {
LeagueDetailGroupId: { editable: false, nullable: true },
GroupName: { validation: { required: true } }
}
}
},
// i seen this is an example from telerik but dont understand the use case for it
parameterMap: function (data, operation) {
// this prints no data before i even start so its a moot point configuring it from products to my stuff at this moment
// but not sure what todo here of if i need this anyways
console.log(data);
if (operation != "read") {
// post the products so the ASP.NET DefaultModelBinder will understand them
var result = {};
for (var i = 0; i < data.models.length; i++) {
var product = data.models[i];
for (var member in product) {
result["products[" + i + "]." + member] = product[member];
}
}
return result;
} else {
return JSON.stringify(data)
}
}
}
});
Here is the grid which works ok with the generic static datasouce object.
var grid = $("#leagueEdit_ldg_grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
autobind: false,
//detailInit: leagueEdit_ldg_detailInit,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "LeagueDetailGroupId",
title: "Group Id",
width: "110px"
},
{
field: "GroupName",
title: "Group Name",
width: "110px"
}
]
});
Delayed read, autobind set to false.
dataSource.read();
Here is my simplified Controller action. It runs and gets data, and works fine for my MVC wrapper grids.
[Route("LeagueDetailGroup_Read/{_leagueTypeId:int}")]
public ActionResult LeagueDetailGroup_Read([DataSourceRequest]DataSourceRequest request, int _leagueTypeId = -1)
{
DataSourceResult result =
_unitOfWork.FSMDataRepositories.LeagueDetailGroupRepository.Get(
ld => ld.LeagueTypeId == _leagueTypeId
)
.ToDataSourceResult(request,
ld => new LeagueDetailGroupViewModel
{
LeagueDetailGroupId = ld.LeagueDetailGroupId,
LeagueTypeId = ld.LeagueTypeId,
GroupName = ld.GroupName,
DateCreated = ld.DateCreated,
DateLastChanged = ld.DateLastChanged
}
);
// data looks fine here
return Json(result, JsonRequestBehavior.AllowGet);
}
Currently i'm getting this error:
Uncaught TypeError: e.slice is not a function
at init.success (kendo.all.js:6704)
at success (kendo.all.js:6637)
at Object.n.success (kendo.all.js:5616)
at i (jquery-3.1.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)
at A (jquery-3.1.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
It's hard to know without testing but let me know how this works.
Change your controller so that you are just returning a json string.
Also, try removing your schema and the parameter map, and set your dataType to json:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("LeagueDetailGroup_Read", "Configuration")?_leagueTypeId=" + leagueTypeId,
dataType: "json"
}
}
});
For the grid I find simple json data does not usually need a schema/model defined. Kendo is super annoying and hard to debug. Let me know how it goes.
In my experience, an e.slice error happens when you have a record that has a null value in it somewhere. The kendo grid is not really smart enough to deal with this so you either have to make sure your datasource returns empty strings instead of nulls for string fields, or put a client template on the columns that translates a null into an empty string. It's possible that the kendo todatasourceresult made the problem come to light. Note that that is usually the last step before returning your dataset since it can modify the entity queries to give paging, so that you never query more than a single page of data (for ajax grids).

Select2 - Pass back additional data via ajax call

Ok, I feel like I'm going crazy here. I'm using the select2 jquery plugin (version 4), and retrieving data via ajax. So you can type in a name, and it will return that contact information. But I also want to return what organization that contact is a part of.
Here is my select2 initialization:
$('#contact_id').select2({
ajax: {
url: 'example.com/contacts/select',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 3,
maximumSelectionLength: 1
});
And here is the data I'm returning (laravel framework):
foreach($contacts as $con) {
$results[] = [
'id' => $con->contact_id,
'text' => $con->full_name,
'org' => [
'org_id' => $con->organization_id,
'org_name' => $con->org_name
]
];
}
return response()->json($results);
So isn't 'org' supposed to be attached to either the created option or select element by select2? So I could do something like $('#contact_id').select2().find(':selected').data('data').org or $('#contact_id').select2().data('data').org or something like that?
Idealistically, this would look like:
<select>
<option value="43" data-org="{org_id:377, org_name:'Galactic Empire'}">Darth Vader</option>
</select>
I swear I confirmed this worked last week, but now it's completely ignoring that org property. I have confirmed that the json data being returned does include org with the proper org_id and org_name. I haven't been able to dig anything up online, only this snippet of documentation:
The id and text properties are required on each object, and these are the properties that Select2 uses for the internal data objects. Any additional paramters passed in with data objects will be included on the data objects that Select2 exposes.
So can anyone help me with this? I've already wasted a couple hours on this.
EDIT: Since I haven't gotten any responses, my current plan is to use the processResults callback to spawn hidden input fields or JSON blocks that I will reference later in my code. I feel like this is a hacky solution given the situation, but if there's no other way, that's what I'll do. I'd rather that than do another ajax call to get the organization. When I get around to implementing it, I'll post my solution.
Can't comment for now (low reputation).. so... answering to slick:
Including additional data (v4.0):
processResults: function (data) {
data = data.map(function (item) {
return {
id: item.id_field,
text: item.text_field,
otherfield: item.otherfield
};
});
return { results: data };
}
Reading the data:
var data=$('#contact_id').select2('data')[0];
console.log(data.otherfield);
Can't remember what I was doing wrong, but with processResults(data), data contains the full response. In my implementation below, I access this info when an item is selected:
$('#select2-box').select2({
placeholder: 'Search Existing Contacts',
ajax: {
url: '/contacts/typeahead',
dataType: 'json',
delay: 250,
data: function(params){
return {
q: params.term,
type: '',
suggestions: 1
};
},
processResults: function(data, params){
//Send the data back
return {
results: data
};
}
},
minimumInputLength: 2
}).on('select2:select', function(event) {
// This is how I got ahold of the data
var contact = event.params.data;
// contact.suggestions ...
// contact.organization_id ...
});
// Data I was returning
[
{
"id":36167, // ID USED IN SELECT2
"avatar":null,
"organization_id":28037,
"text":"John Cena - WWE", // TEXT SHOWN IN SELECT2
"suggestions":[
{
"id":28037,
"text":"WWE",
"avatar":null
},
{
"id":21509,
"text":"Kurt Angle",
"avatar":null
},
{
"id":126,
"text":"Mark Calaway",
"avatar":null
},
{
"id":129,
"text":"Ricky Steamboat",
"avatar":null
},
{
"id":131,
"text":"Brock Lesnar",
"avatar":null
}
]
}
]

Using Select 2 with ASP.NET MVC

I am working on an ASP.NET MVC 4 app. In my app, I'm trying to replace my drop down lists with the Select 2 plugin. Currently, I'm having problems loading data from my ASP.NET MVC controller. My controller looks like this:
public class MyController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<MyItem>))]
public IHttpActionResult Get(string startsWith)
{
IEnumerable<MyItem> results = MyItem.LoadAll();
List<MyItem> temp = results.ToList<MyItem>();
var filtered = temp.Where(r => r.Name.ToLower().StartsWith(startsWith.ToLower());
return Ok(filtered);
}
}
When I set a breakpoint in this code, I notice that startsWith does not have a value The fact that the breakpoint is being hit means (I think) my url property below is set correct. However, I'm not sure why startsWith is not set. I'm calling it from Select 2 using the following JavaScript:
function formatItem(item) {
console.log(item);
}
function formatSelectedItem(item) {
console.log(item);
}
$('#mySelect').select2({
placeholder: 'Search for an item',
minimumInputLength: 3,
ajax: {
url: '/api/my',
dataType: 'jsonp',
quietMillis: 150,
data: function (term, page) {
return {
startsWith: term
};
},
results: function (data, page) {
return { results: data };
}
},
formatResult: formatItem,
formatSelection: formatSelectedItem
});
When this code runs, the only thing I see in the select 2 drop down list is Loading failed. However, I know my api is getting called. I can see in fiddler that a 200 is coming back. I can even see the JSON results, which look like this:
[
{"Id":1,"TypeId":2,"Name":"Test", "CreatedOn":"2013-07-20T15:10:31.67","CreatedBy":1},{"Id":2,"TypeId":2,"Name":"Another Item","CreatedOn":"2013-07-21T16:10:31.67","CreatedBy":1}
]
I do not understand why this isn't working.
From the documentation:
Select2 provides some shortcuts that make it easy to access local data
stored in an array...
... such an array must have "id" and "text" keys.
Your json object does not contain "id" or "text" keys :) This should work though i have not tested it:
results: function (data, page) {
return { results: data, id: 'Id', text: 'Name' }
}
There's further documentation following the link on alternative key binding... I believe thats where your problem lies.
Hopefully this helps.

Categories

Resources