javascript and jquery weird array object - javascript

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

Related

How to return first item from a nested JSON array using jQuery

I'm currently experiencing a few problems whilst parsing .JSON.
Ok, so 'element.lineStatuses' can return 1 or 2 opjects in an array but I only want to return the first object from array. I've tried a multitude of different solutions, however, none seem to work...
Please note: I am unable to use '$.first()' as a solution as my application depends on an older version of jQuery.
$.ajax({
url:"https://api.tfl.gov.uk/line/mode/tube,overground,dlr,tflrail/status",
dataType: 'json',
type: 'get',
cache: false,
beforeSend: function() {
$("#loadingDiv").show();
},
success: function(data){
console.log(data);
var jObject = data;
$.each(jObject, function(index, element) {
$("#lines").append("<li class=\"lineName\"><h2>" + element.name + "</h2></li>");
// console.log(element.name);
// element.lineStatuses; can contain 1 or 2 opjects in an array but i only want to return the first objectin array.
var status = element.lineStatuses;
// loop to get line status
// gets all objects
$.each(status, function(index, element) {
var desc = element.statusSeverityDescription;
//console.log(desc);
$("#lines").append("<p class=\"currentStatus\">" + desc + "</p>");
});
});
}// end success
});// end ajax
If you what you want is to get only the first element of an array-like object in an array of its own, you can use slice to create a shallow copy:
var status = [].slice.call(element.lineStatuses, 0, 1);
If you're sure element.lineStatuses is an array and not simply array-like you can use the simpler:
var status = element.lineStatuses.slice(0, 1);
Try this:
var status = element.lineStatuses[0];

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)

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

SharePoint 2013 ClientContext : How to DELETE specific list items by MULTIPLE CONDITION filter?

By using SP.ClientContext from Javascript end, below is the code i used to "UPDATE" a list item. Simply:
var clientContext = new SP.ClientContext( siteURL );
spList = clientContext.get_web().get_lists().getByTitle( myListName );
this.spList_ExistingItem = spList.getItemById( itemID );
spList_ExistingItem.set_item( 'FullName', myFullName );
spList_ExistingItem.set_item( 'Age', myAge );
spList_ExistingItem.update();
clientContext.executeQueryAsync(succeeded_handler, fail_handler);
This allows me to update an list item by querying it by ONE condition which is: getItemById(itemID) here.
Now let's say i want to delete any item which is:
Age = 30
Country = US
Then how do i do such query with multiple conditions. And then even to DELETE please?
UPDATED
According to the answer below, i found the REST API is more easier and cleaner to use for Client/Javascript end, compared to CSOM. (So then, of course i changed all my codes to the REST API way already.)
So the conclusion is, i suggest to use REST API rather than CSOM (SP.ClientContext).
Thanks! :)
This can be done in two different ways, either by using CSOM/JSOM or via the SharePoint REST API. Since you are using the CSOM/JSOM model in your question, I'll only show you how it's done using that method.
Using CSOM/JSOM
To filter SP.ListItem's on mulitple conditions, there are no single methods that take the arguments as multiple filter fields. Instead, you'll have to resort to using a CAML query to specify the list items you want, as below.
var clientContext = new SP.ClientContext( siteURL );
spList = clientContext.get_web().get_lists().getByTitle( myListName );
//Create a CAML-query with your filter conditions
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Age\'/>' +
'<Value Type=\'Number\'>30</Value></Eq>
<Eq><FieldRef Name=\'Country\'/>' +
'<Value Type=\'Text\'>US</Value></Eq></And></Where></Query><RowLimit>10</RowLimit></View>');
//The query will return a collection of items matching your conditions
this.collListItem = spList.getItems(camlQuery);
clientContext.load(collListItem);
//Execute the query
clientContext.executeQueryAsync(function () {
var itemCount = collListItem.get_count();
//For each list item in the collection, mark it to be deleted
for (var i = itemCount - 1; i >= 0; i--) {
var oListItem = collListItem.itemAt(i);
oListItem.deleteObject();
};
//Execute the delete operation
clientContext.executeQueryAsync(deleteSucceeded, deleteFailed);
}, fail_handler);
Using SharePoint REST API
This method assumes that you use jQuery to be able to do some simple $.ajax() calls and use the promise functionality, since you might have multiple items to delete. It also assumes that you understands how you can use jquery deferred objects to chain asynchronous functions to run in sequence.
The simple idea is to
Make a request to the REST api and get all the items matching your filter conditions
For each object in the collection returned, make another request that deletes the item, and add the request to an array of requests
When all requests are done, do whatever you want!
Note that you might have to modify the REST api call to match your columns. Just use the browser or Postman to check that your request is correct.
function getItemsToDelete () {
//You might have to modify this so it filters correctly on your columns
var requestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(" + myListName + ")/items?$filter=Age eq 30 and Country eq 'US'")
//Return and ajax request (promise)
return $.ajax({
url: requestUrl,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(result) {
$.each(result.d.results, function(index, item){
//Note that we push the ajax-request to the array
//that has been declared a bit down
itemsToDelete.push(deleteItem(item));
});
},
error: function(error) {
//Something went wrong when retrieving the list items
}
});
}
function deleteItem (item) {
//All SP.ListItems holds metadata that can be accessed in the '__metadata' attribute
var requestUrl = item.__metadata.uri;
return $.ajax({
url: requestUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": item.__metadata.etag,
"X-HTTP-Method": "DELETE"
},
success: function() {
console.log("Item with ID " + item.__metadata.id + " successfully deleted!");
},
error: function(error) {
//Something went wrong when trying to delete the item
}
});
}
//Declare an array of deferred objects that hold a delete request
//for each item that is to be deleted
var itemsToDelete = [];
//First get the items to delete
$.when(getItemsToDelete()).then(function () {
$.when.apply($, itemsToDelete).then(function(){
console.log("All items are deleted!");
});
});
Some useful sources
jQuery Deferred object
CRUD operations on list items with SharePoint REST api

Accessing items in array

I have an object returned from a $.ajax request. This is an example:
[{"id":"14","branchName":"Catcliffe","address1":"26 Main Street","address2":"","address3":null,"city":"Catcliffe","county":"South Yorkshire","postcode":"S60 5SR","country":"UK"}]
I am having a brain freeze on how to access items in the array, for example how would I set a variable to the 'branchName'...
This is the code I used to get the data:
$("#branchID").change(function(){
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch){
$("div#results").html(branch);
}
});
});
You need to get the first element in the returned array using it's index, [0], then you can grab the property you want from that, .branchName.
$("div#results").html(branch[0].branchName);
Example fiddle
I just assumed that you are holding that object in a variable called xObj.
Try,
console.log(xObj[0].branchName)
But you should parse it before accessing the values since you have not mentioned the type,
var xObj = JSON.parse(branch);
console.log(xObj[0].branchName)
You have to use indexer, to access the element of array. As array contains object you go to use dot . operator to access object properties like branchName
Live Demo
$("div#results").html(branch[0].branchName);
Your code would be
$("#branchID").change(function () {
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function (branch) {
$("div#results").html(branch[0].branchName);
}
});
});
You would get the branchName property from the first (and only) item in the array:
$("div#results").html(branch[0].branchName);
use object and using its property we can access it branch[0].branchname
$("#branchID").change(function()
{
var id = $(this).val();
$.ajax(
{
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch)
{
var branchname= branch[0].branchname;
$("div#results").html(branch);
}
});
});
To handle multiple objects you can loop the result using a for loop like the one given below:
for(var i in branch)
{
var id = branch[i].id;
var branchName = branch[i].branchName;
//....
//Iterate other objects as well
}

Categories

Resources