OData get URI of individual Entity - javascript

I'm developing in SAPUI5 and I'm retrieving an EntitySet via an OData read function. My code looks like this:
oDataModel.read("/Products", {
success: function(oData) {
oData.results.forEach(function(element, index, array) {
*// Here I want to get the Request URI for this specific element*
});
}
});
In the forEach function I want to retrieve the URI for the specific Entity from the EntitySet.
So for example I want to retrieve the URI like this:
"/Products(ID='1')"
"/Products(ID='2')"
Is this possible?

You could simply get the URL by creating it with the Entity Key values.
oDataModel.read("/Products", {
success: function(oData) {
oData.results.forEach(function(element, index, array) {
var sEntity = "/Products(ID='"+element.ID+"')";
});
}
});

Related

How can I assign dictionary values to javascript variables (jQuery / AJAX API call returned in JSON)

I have a well running AJAX request that queries data from a third party API that returns the data in JSON. I now want to assign the values from the returned JSON data to javascript variables to make further manipulation to the data itself in my AJAX success function before updating the frontend.
In the below example I would like to assign the value of key name to my Javascript team variable.
What would be the best way to accomplish this?
This is the returned structure:
{
"api":{
"results":1,
"teams":[
{
"team_id":66,
"name":"Barcelona",
"code":null,
"logo":"Not available in Demo",
"country":"Spain",
"founded":1899,
"venue_name":"Camp Nou",
"venue_surface":"grass",
"venue_address":"Carrer d'Ar\u00edstides Maillol",
"venue_city":"Barcelona",
"venue_capacity":99787
}
],
This is my AJAX request:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/http://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_data = response
console.log(team_data)
team = // how to assign team name from API callback to variable
console.log(team)
$("#selectedClub").html(response);
}
});
});
You can use dot notation to navigate through objects
team_data.api.teams[0].name //output: "barcelona"
In you example there is only one item inside teams array, so the above example should works fine, but let's suppose that in your response there is more than 1 team on teams then you could do something like this:
var teamList = [];
$.each(team_data.api.teams, function(index, team){
teamList.push(team.name);
})
and it will give an array with all team names from your ajax response
put JSON in js obj variable
var obj = JSON.parse('{ <key:value>,<key:value>...}');
Make sure the text is written in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("name").innerHTML = obj.name + ", " + obj.country;
</script>

Grab data from JSON using JSON data as var

I trying to grab the url of an attached photo using json. Im using the value of the data from the json "HousePhoto1". I then want to use that value to grab the value from the post_media data. This is what im using at the moment, but my javascript doesn't load correctly when I try this, but if i take to .guid away, my page loads but without any json data. I have also added a photo of my json.
$.getJSON( "https://example.co.uk/wp-json/wp/v2/posts?&per_page=1&page=1", function( data ) {
$.each( data, function( key, val ) {
var photo = val.post_media[val.HousePhoto1].guid;
});
});
<img src="'+photo+'"/>
Image of my json
You were almost there. However, it looks like you are receiving an array back from your JSON response. Using a simplified dataset as my example, you can probably do something like this:
var data = [
{
HousePhoto1: "7073",
post_media: {
7073: {
guid: "https://somecoolphoto.com"
}
}
},
{
HousePhoto1: "7085",
post_media: {
7085: {
guid: "https://anothercoolphoto.com"
}
}
},
];
$.each(data, function(index, value) {
var housePhotoId = value.HousePhoto1;
var photo = value.post_media[housePhotoId].guid;
});
Also, if you are attempting to set multiple images, you cannot do it the way you currently are. You should dynamically insert the image into the DOM inside each iteration of the each loop via JavaScript.

Retrieve data from Chrome localStorage

I have an Array storing objects each with another array inside. I'm using the Chrome Storage API to store these objects (for an extension). Writing data works fine, but I can't seem to extract the data I need:
Write to storage:
function writeToStorage(form) {
var formObjectsArr = [];
var data = [];
var formData;
$(':input', '#' + form)
.each(function() { data.push(this.value); })
.promise()
.done(function() {
var formData = new Form(data);
formObjectsArr.push(formData);
chromeStorage(formObjectsArr);
});
}
function chromeStorage(formObjectsArr) {
chrome.storage.sync.set({list:formObjectsArr}, function() {
console.log('Settings saved');
});
}
function Form(data) { this.data = data; }
Read from storage (not sure what to do here - the current function simply returns an object which contains an array which contains the object that contains the array I want to access):
function getFromStorage() {
chrome.storage.sync.get({list:[]}, function(test) {
console.log(data)
});
}
You can specify a string, array of strings, or a object dictionary to retrieve data stored in chrome extension's local or sync storage. Since you only want to retrieve the list keyed data, you can just use a string for the first argument of the sync.get method.
function getFromStorage() {
chrome.storage.sync.get("list", function(data) {
console.log(data);
});
}

pass collection of objects through http post in angular js

I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Categories

Resources