how can I parse this javascript array using Map function? - autocomplete

I want to parse the below JavaScript array for using in Autocomplete control.
The requirement is to display the value field in autocomplete textbox and store the key field as itemID.
{"Key":9886,"Value":"xxx"},{"Key":9887,"Value":"yyy"},{"Key":5634,"Value":"zzz"},{"Key":9888,"Value":"abcd"}
I tried the below code to map this array as source for my textbox:
var itemID;
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data:JSON.stringify({'term' :request.term}),
dataType: 'json',
contentType: 'application/json',
success: function(data) {
response(
$.map(data,
function(object) {
return {
label: object.value,
value: object.key
}
})
)
},
error: function(xhr, status, error) {
alert(error);
}
});
},
minLength: 2,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.value);
itemID = ui.item.key;
}
});```
Appreciate any help on this.

The below code worked to map autocomplete source to dictionary array:
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data: JSON.stringify({ 'term': request.term }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var parsedData = JSON.parse(data);
var arr = $.map(parsedData,
function (item) {
return {
label:item.Value,
value:item.Key
}}
);
response(arr);
},
error: function (xhr, status, error) {
alert('here');
var array = [];
response(array);
}
});
},
minLength: 3,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.label);
userID = ui.item.value;
}
});
The controller code which returns dictionary was this:
public ActionResult Getdata(string term)
{
var itemList= Provider.GetAllItems();
var filteredItems = itemList.Where(x => x.Value.Contains(term));
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(filteredItems );
return Json(result, JsonRequestBehavior.AllowGet);
}

Related

Hosting a Forge Autodesk viewer on Github

I've an issue with the Forge viewer I'm developping : Im' trying to host it using Github-page, but it doesn't seem to work correctly.
The issue is on the File tree : when I load the viewer page from the Github pages, the file tree seems stuck on "Loading...". However, it correctly loads when I load the page from localhost.
The code of the File tree :
$(document).ready(function () {
prepareAppBucketTree();
$('#refreshBuckets').click(function () {
$('#appBuckets').jstree(true).refresh();
});
$('#createNewBucket').click(function () {
createNewBucket();
});
$('#createBucketModal').on('shown.bs.modal', function () {
$("#newBucketKey").focus();
})
$('#hiddenUploadField').change(function () {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
});
});
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.log(bucketKey)
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function prepareAppBucketTree() {
$('#appBuckets').jstree({
'core': {
'themes': { "icons": true },
'data': {
"url": '/api/forge/oss/buckets',
"dataType": "json",
'multiple': false,
"data": function (node) {
return { "id": node.id };
}
}
},
'types': {
'default': {
'icon': 'glyphicon glyphicon-question-sign'
},
'#': {
'icon': 'glyphicon glyphicon-cloud'
},
'bucket': {
'icon': 'glyphicon glyphicon-folder-open'
},
'object': {
'icon': 'glyphicon glyphicon-file'
}
},
"plugins": ["types", "state", "sort", "contextmenu"],
contextmenu: { items: autodeskCustomMenu }
}).on('loaded.jstree', function () {
$('#appBuckets').jstree('open_all');
}).bind("activate_node.jstree", function (evt, data) {
if (data != null && data.node != null && data.node.type == 'object') {
// $("#MyViewerDiv").empty();
var urn = data.node.id;
getForgeToken(function (access_token) {
jQuery.ajax({
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn + '/manifest',
headers: { 'Authorization': 'Bearer ' + access_token },
success: function (res) {
if (res.status === 'success') callByUrn('urn:'+urn);
else $("#MyViewerDiv").html('The translation job still running: ' + res.progress + '. Please try again in a moment.');
},
error: function (err) {
var msgButton = 'This file is not translated yet! ' +
'<button class="btn btn-xs btn-info" onclick="translateObject()"><span class="glyphicon glyphicon-eye-open"></span> ' +
'Start translation</button>'
$("#MyViewerDiv").html(msgButton);
}
});
})
}
});
}
function autodeskCustomMenu(autodeskNode) {
var items;
switch (autodeskNode.type) {
case "bucket":
items = {
uploadFile: {
label: "Upload file",
action: function () {
uploadFile();
},
icon: 'glyphicon glyphicon-cloud-upload'
}
};
break;
case "object":
items = {
translateFile: {
label: "Translate",
action: function () {
var treeNode = $('#appBuckets').jstree(true).get_selected(true)[0];
translateObject(treeNode);
},
icon: 'glyphicon glyphicon-eye-open'
}
};
break;
}
return items;
}
function uploadFile() {
$('#hiddenUploadField').click();
}
function translateObject(node) {
$("#MyViewerDiv").empty();
if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = node.parents[0];
var objectKey = node.id;
jQuery.post({
url: '/api/forge/modelderivative/jobs',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'objectName': objectKey }),
success: function (res) {
$("#MyViewerDiv").html('Translation started! Please try again in a moment.');
},
});
}
Please note that Github Pages are used for serving static pages without any special server-side logic. Your Forge application requires a server to talk to as well, for example, to obtain a list of buckets for the tree view (by making a request to /api/forge/oss/buckets).
You could potentially host your application's server-side logic on something like Heroku, and then have your static HTML/CSS/JavaScript page on Github talk to that server (for example, https://my-forge-app.herokuapp.com/api/forge/oss/buckets). Just be careful about CORS.

How to add additional headers and token for each tile request

We are using mapbox gl js with custom tile providers and tiles are protected by token. In our case each tile will have its own token and fetched via AJAX request on demand. In order to achieve this i tried to use tranformRequest option like below but none of them works
Method 1 Returning promise
var map = new mapboxgl.Map({
container: 'map',
style: 'https://www.example.com/styles/streets/style.json',
center: [53.33, 24.5],
zoom: 8,
transformRequest: function(url, resourceType) {
if(resourceType !== 'Tile') {
return {
url: url,
};
}
return axios.get('../api/get-token.php', {
params: {
AccessURL: url
},
headers: {
'X-Requested-With': 'XmlHttpRequest'
}
}).then(function (response) {
return {
url: url,
headers: {
'X-Requested-With': 'XmlHttpRequest'
'token': response.data.token
}
}
});
}
});
Method 2 async/await
var map = new mapboxgl.Map({
container: 'map',
style: 'https://www.example.com/styles/streets/style.json',
center: [53.33, 24.5],
zoom: 8,
transformRequest: async function(url, resourceType) {
if(resourceType !== 'Tile') {
return {
url: url,
};
}
try {
const response = await axios.get('../api/get-token.php', {
params: {
AccessURL: url
},
headers: {
'X-Requested-With': 'XmlHttpRequest'
}
});
return {
url: url,
headers: {
'X-Requested-With': 'XmlHttpRequest'
'token': response.data.token
}
};
} catch (error) {
return {
url: url,
};
}
}
});
How can i achieve this cases? is there any options exists in mapbox gl js library or any workaround ?
I don't believe transformRequest can accept an async parameter such as a promise. It expects to call a function and immediately receive an object containing url and headers:
{
...
transformRequest: function transformRequest(url, resourceType) {
if (resourceType === 'Tile' && url.match('...')) {
return {
url: url,
headers: { 'Authorization': 'Basic ' + btoa('MyPassword') }
};
}
}
If your use case truly requires a unique authentication token for every single tile (which seems...unusual!) then I'm not aware of a method which will work.

How to use include "users" in restangular login?

I want to store token and user information in local storage ,things like store token and userId are okay except I can't include users detail information like email
this.login = function (data) {
var loginResults = Restangular.one('/users/login')
.post(undefined, data)
.then(function (data) {
var mytoken = data.id;
storeToken(data);
Restangular.setDefaultHeaders({ accept: 'application/json', access_token: mytoken });
},
function (Response) {
console.log("There was an error.");
});
return loginResults;
}
Finally I got the correct answer to include "user" here is the result....
this.login = function (data) {
var loginResults = Restangular.one('/persons/login')
.post(undefined, data, {
include: "user"
})
.then(function (data) {
var mytoken = data.id;
storeToken(data);
Restangular.setDefaultHeaders({ accept: 'application/json', access_token: mytoken });
$state.go('home');
}, function (Response) {
console.log("There was an error.");
alert("Login Failed");
});
return loginResults;
}

Share custom story with staged image on Facebook using FB.ui no working

I have the following code that stage the canvas image and then create object to share it using FB.ui. Staging the image and create the object are working without problem but the share dialog not displayed. If I replaced the image parameter in create object with an image url it is working.
is there any wrong in my code:
var userAccessToken = $("#user_access_token").val();
var appAccessToken = $("#app_access_token").val();
try {
blob = dataURItoBlob(dataURL);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", userAccessToken);
fd.append("file", blob);
try {
var imageURI;
$.ajax({
url: "https://graph.facebook.com/me/staging_resources",
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data['uri']);
imageURI = data['uri'];
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:true
},
description: ""
}
},
function(response) {
var objectId = response['id'];
FB.ui({
method: 'share_open_graph',
action_type: 'myappnamespace:myaction',
action_properties: JSON.stringify({
myobject:objectId
})
}, function(response){});
}
);
}
});
} catch (e) {
console.log(e);
}
finally I found the solution by changing user_generated parameter from true to false
now the code for creating object looks like below:
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:false
},
description: ""
}
}

ASP.NET MVC 2: jQuery post string is null?

I'm not sure what's the issue, but I'm constructing a string and trying to pass it to my Controller Action. But when the action is executed, the data is null.
JavaScript:
var xml = "<Request><ZipCode>92612</ZipCode></Request>";
$.ajax({
url: "/Home/GetXml",
contentType: 'application/text; charset=utf-8',
data: xml,
success: function (result) { success(result); },
type: "POST",
datatype: "text"
});
Controller:
[HttpPost]
public ActionResult GetXml(string data)
{
if (!String.IsNullOrEmpty(data))
{
return View("Index", data);
}
return View("Index");
}
If I set a breakpoint on the if, the "data" is null. What gives?
The answer: don't use contentType
Thanks to this question and answer:
Asp.Net Mvc JQuery ajax input parameters are null
try with
$.ajax({
url: "/Home/GetXml",
contentType: 'application/text; charset=utf-8',
data: { data: xml },
success: function (result) { success(result); },
type: "POST",
datatype: "text"
});