pass collection of objects through http post in angular js - javascript

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)
{
}

Related

Removing values from array and adding them to POST method request

I have a cart in my AngularJS app and I need to identify the items through their id through a POST method.
They are stored in an array called patent_ids and are appended to the request like so:
var cartArr = [];
var cartItems = ngCart.getItems()
cartItems.forEach(function(currentValue, index, array){
cartArr.push(currentValue._id)
})
var obj = {
patent_id: cartArr
};
fetchBasketPatents(obj);
function fetchBasketPatents(obj) {
//load of code to call service and pass the ids
}
var REST_SERVICE_URI = 'http://localhost:8080/p3sweb/rest-basket/';
factory.fetchBasketPatents = function(ids) {
var deferred = $q.defer();
$http.post(REST_SERVICE_URI, ids) //REQUEST TO BACK END WITH IDS
.then(
function(response){
deferred.resolve(response.data)
},
function(errResponse){
deferred.reject(errResponse)
}
)
return deferred.promise;
}
It works but it would be easier if rather than sending the ids in a named array, they could be sent as an anonymous array, or even better each item extracted an inserted into an anonymous object.
Question
How do I send the ids in the POST request in either an anonymous array or object? Apologies if I am missing something obvious.
How do I send the ids in the POST request in either an anonymous array or object?
From Document:
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Where data – {string|Object}
So the answer is: you cannot define anonymous array but object only (like you did)

URL parameters on javascript

I´m making a call using javascript and I would like to send an array:
var selected = [];
selected=getAllEnginesIdsSelected();
console.log("selected: "+selected);
$.getJSON('/call/' + selected,
function(myList) {
The funcion that I use in Javascript to retrieve array is:
function getAllEnginesIdsSelected() {
var selected = [];
$("input:checkbox[id^='engine_']:checked").each(function(){
var ele=$(this)[0].id;
selected.push(ele);
});
return selected;
}
Console.log retrieves selected: 2,5
In MVC Controller I have
#RequestMapping(method = RequestMethod.GET, value = "/call/{selected}")
public List<List<myList>> myCall(#RequestParam(value="selected[]") String[] selected){
I gives an error. I don´t want to use AJAX. This is posible to send?
selected is an array, which you are joining to a string in the URL. Try something like $.getJSON('/call/?selected=[' + selected.join(',')]

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);
});
}

Restful call from angular is not returning results

Here am trying to make a RESTful call to an external API.
am trying to achieve 2 things in one call. So, I have one function with 2 nested functions within.
The first one calls the search API to search for a product.
The second one calls recommended API to retrieve recommendations based on the results from the first one.
My AngularJS Code is as follow;
var walmartAssn= angular.module('myApp', ['ngResource']);
walmartAssn.controller('walmartAssnController', function($scope,$resource) {
//define the API urls
var urlSearchProductApi= 'http://api.walmartlabs.com/v1/search';
var urlRecProductApi='http://api.walmartlabs.com/v1/nbp';
//define API key
var keyApi='exampleKey123';
$scope.searchProductMethod= function(){
//pass the value from the user input text box
$scope.searchItem = $scope.item ;
$scope.productId;
//get the data from the Walmart product search API
searchRequest = $resource(urlSearchProductApi, { callback:
"JSON_CALLBACK" }, { get: { method: "JSONP" }});
//pass the input text as a parameter through a GET request
$scope.searchedProducts = searchRequest.get({ apiKey: keyApi,
query: $scope.searchItem });
console.log($scope.searchedProducts.$promise);
$scope.searchedProducts.$promise.then(function(eventDetail){
//fetch the ID of the first item
$scope.productId = eventDetail.items[0].itemId;
});
recommendRequest = $resource(urlRecProductApi, { callback:
"JSON_CALLBACK" }, { get: { method: "JSONP" , isArray:true}});
console.log(recommendRequest);
$scope.recommendedProducts = recommendRequest.get({ apiKey:
keyApi, itemId: 42608121 });
console.log($scope.recommendedProducts)
$scope.recommendedProducts.$promise.then(function(){
$scope.recommendedProductsList = eventDetail;
console.log("Print recommended list");
console.log(eventDetail);
console.log($scope.recommendedProductsList);
console.log('End');
});
} });
In the above app, the first function returns result while the second function does not.
In chrome console am getting the following, not the fist function returns an array of JSONs while the second one was blocked.
While on the Network tab in the chrome console, i see the the call was successful, as in shown below;
Moreover, I have tried the URL with hard coded values in the browser and worked successfully.
Any help is appreciated, thanks in advance.
Assuming that the 2nd call does not depend on the first, I see that you are not defining eventDetail as an argument to the second method.
So, instead of:
$scope.recommendedProducts.$promise.then(function(){
It would be:
$scope.recommendedProducts.$promise.then(function(eventDetail){
If you actually mean to use the eventDetail from the first method (the one used with $scope.searchedProducts.$promise), then the whole second request code needs to be called from the first then handler, passing the data needed.
Something like:
var walmartAssn= angular.module('myApp', ['ngResource']);
walmartAssn.controller('walmartAssnController', function($scope,$resource) {
//define the API urls
var urlSearchProductApi= 'http://api.walmartlabs.com/v1/search';
var urlRecProductApi='http://api.walmartlabs.com/v1/nbp';
//define API key
var keyApi='exampleKey123';
$scope.recommend = function(itemId) {
var recommendRequest = $resource(urlRecProductApi, { callback:
"JSON_CALLBACK" }, { get: { method: "JSONP" , isArray:true}});
console.log(recommendRequest);
$scope.recommendedProducts = recommendRequest.get({ apiKey:
keyApi, itemId: itemId });
console.log($scope.recommendedProducts);
$scope.recommendedProducts.$promise.then(function(eventDetail){
$scope.recommendedProductsList = eventDetail.items; // or just `eventDetail`?
console.log("Print recommended list");
console.log(eventDetail);
console.log($scope.recommendedProductsList);
console.log('End');
});
};
$scope.searchProductMethod= function(){
//pass the value from the user input text box
$scope.searchItem = $scope.item ;
$scope.productId;
//get the data from the Walmart product search API
var searchRequest = $resource(urlSearchProductApi, { callback:
"JSON_CALLBACK" }, { get: { method: "JSONP" }});
//pass the input text as a parameter through a GET request
$scope.searchedProducts = searchRequest.get({ apiKey: keyApi,
query: $scope.searchItem });
console.log($scope.searchedProducts.$promise);
$scope.searchedProducts.$promise.then(function(eventDetail){
//fetch the ID of the first item
$scope.productId = eventDetail.items[0].itemId;
$scope.recommend($scope.productId);
});
};
});
One more thing:
Why is isArray:true used only in recommendation but not in search?
Update
It might be worth trying a jQuery JSONP call to see if it works. Maybe the recommendation endpoint does not support JSONP. AngularJS returns 404 in this case according to https://stackoverflow.com/a/24893912/146656

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