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)
Related
i have stuck on this weird thing for 03 day and don't understand why it created that object "id[]" when jquery sending data to server. i tried to push the element to new array so i can get the normal {id: 'value01'} but it does not work, the server response is still showing the weird array in object: {'id[]': 'value01}. i am stuck on this because if i do var id = masoid[0] it work as the server show normal {id: 'value01'} but i need to filter the array before sending it. Thank you for your time
here is jquery code
function onlyUnique(value, index, self) {
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
if(isNumeric(value)){
return self.indexOf(value) === index;
}
};
// var id = {masoid.filter(onlyUnique)};
// var idDaFilter = new Array;
// id.forEach(element => {
// idDaFilter.push(element);
// });
var id = masoid.filter(onlyUnique);
console.log(id);
$.ajax({
url: deleteUrl,
type: 'POST',
data: {id:id},
});
the server response:
server code
let id = JSON.parse(JSON.stringify(req.body));
console.log(req.body);
You're using the method filter in the variable id. This method return a new array (shallow of original), so this is why you're getting 'id[ ]' on response. Use find instead.
var id = masoid.find(onlyUnique);
See an example here.
When you set var id = masoid[0] you're getting the first element of that array, than it works.
See more details on documentation find method and filter method
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>
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)
{
}
I am developing a web application retrieving data from several web services (let's say only two to simplify). What has to be retrieved from one service does not depend on what has been retrieved from the other, so I can launch AJAX requests in parallel. I need then to perform some actions once both queries have returned their data. Since it seems to be something very usual, I am wondering if there is a well-formalised and accepted design pattern to do that. What I am doing so far is there (using jquery):
var data1 = null;
var data2 = null;
$.ajax({
url : url1,
success: function(data) {
data1 = data;
if(data2) perform();
},
});
$.ajax({
url : url2,
success: function(data) {
data2 = data;
if(data1) perform();
},
});
function perform() {
//do interesting stuff on data1 and data2
}
Would you do like that as-well ?
you can do like this
Check : jQuery: api.jquery.com/jquery.when
we can use jQuery's $.when() method, which takes a list of these "Deferred" objects (All jQuery Ajax methods return Deferred objects) and then provides a single callback.
Syntax
$.when(
// Deferred object (probably Ajax request),
// Deferred object (probably Ajax request),
// Deferred object (probably Ajax request)
).then(function() {
// All have been resolved (or rejected), do your thing
});
Example :
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
When I have multiple ajax queries I usually like to keep a list of URLs. I create a list of promises and apply the $.when function to them. Something like this:
var urls = [url1, url2];
var endpoints = [];
for (var i = 0; i < a.length; i+=1) {
endpoints.push($.ajax(urls[i]));
}
$.when.apply($, endpoints).done(function () {
// Function arguments array differs if we have one or more than one endpoint.
// When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR].
// When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...].
// Normalize the single endpoint to the generic list one.
var args = endpoints.length > 1 ? arguments : [arguments];
});
Or more concise:
var urls = ['page1', 'page2'];
$.when.apply($, $.map(urls, $.ajax)).done(function () {
console.log(arguments);
});
So I have a Resource defined as follows:
angular.module('questionService', ['ngResource'])
.factory('QuestionService', function($http, $resource) {
var QuestionService = $resource('/api/questions/:key', {}, {
query: {
method:'GET',
isArray:true,
},
save: {
method: 'POST',
}
});
return QuestionService
});
And later on I take some form input and do the following
var newQ = {
txt: $scope.addTxt
};
QuestionService.save(newQ)
The server responds to the POST request both by reissuing the JSON for the object and setting the location header with the new unique ID. The problem is that Angular is not saving that returned JSON or the location header into the object and it is not getting set with the ID from the server for future operations. I've tried a number of things such as:
transformResponse: function(data, headersGetter) {
locationHeader = headersGetter().location;
key = locationHeader.split('/').slice(-1)[0];
data.key = key;
return data;
}
However the returned data item doesn't seem to be getting used. Am I missing something? This seems like a pretty common use case for interacting with a REST api.
Thanks!
You need to have a success handler to assign the new id to newQ manually:
QuestionService.save(newQ, function(data) {
newQ.id = data.id;
});
But there is a better to achieve the same. Because your QuestionService is a resource class object, you can instantiate your newQ like this:
var newQ = new QuestionService({text: $scope.addTxt});
Then, call $save() of newQ:
newQ.$save();
Now newQ should have the new id returned by the server.
I have Asp.Net server with WebApi2 running, i use Ok(number) to return content, and it return for example '6' as result. once it return, the angular show an object containing promise and state, and prototypes and a deep repeated hierarchy, but no value, no '6'.
So i went to see where the data goes, for seeing where the data is i define a transform, and i see awo the data, but it's not a json...
later i change it to following, and now i have a obj in my success function, which has sub property called 'returnValue' (as i defined), and this object hold my value.
transformResponse: function(data, header){
var obj={};
obj.returnValue=angular.fromJson(data);
return obj;
},