i am using jquery to send json data that contains array of elements like this
$('#brand_category').click(function(event){
category = $("input:checkbox[name=category]:checked").map(function() {
return this.value;
}).get();
brand = $("input[type='radio']:checked").map(function() {
return this.value;
}).get();
parameter.push({
brand : brand,
category: category
});
var json = JSON.stringify(parameter)
$.ajax({
type: 'post',
url: "{% url 'seller_details' %}",
data: {'parameter[]' : json , csrfmiddlewaretoken:'{{csrf_token}}'},
success: function(data){
},
error:function (response, error){
}
});
and in the view i am collecting the data like this
brand_category = self.request.POST.get('parameter[]')
print brand_category
this prints the data as this
[{"brand":["spykar"],"category":["Women Clothing","Dresses"]},{"brand":["Madame"],"category":["Women Clothing","Dresses"]}]
then i tried to loop through the json like this
for list in list_data:
brand = list_data['brand']
print brand
categories = list_data['category']
print categories
but i am getting the error as this
list indices must be integers, not str
how can i loop through the json data to get the list of brands and categories?
Your outer loop is a list, and then you loop through each dictionary in the list. Also, you have to convert the string to a python object.
import json
brand_category = self.request.POST.get('parameter[]')
Lbrand_category = json.loads(brand_category)
for D in Lbrand_category:
brand,categories = D['brand'],D['category']
Note: if you want only the brand string, without the list, use:
brand,categories = D['brand'][0],D['category']
I recommend you this AJAX Request (Its more clear):
$('#brand_category').click( sendAjax );
function sendAjax()
{
var category = $("input:checkbox[name='category']:checked").val();
var brand = $("input[type='radio']:checked").val();
var data = { "category" : category, "brand" : brand, "csrfmiddlewaretoken" : '{{csrf_token}}' }
$.ajax({
type: 'post',
url: "{% url 'seller_details' %}",
data: data,
success: function(data)
{
//console.log(data) // Print the response of Django or see this in "Network" request, F12 Chrome
},
error:function (response, error)
{
}
});
}
View:
category = request.POST['category']
print category
brand = request.POST['brand']
print brand
List data of brands in JavaScript:
var data = {} //This is a empty object named data
data.brans = [];
and then you need create a for select all brands
for ("list of brands"){
brand_name = logic
data.brands.push(brand_name)
} //This is only a idea
Related
I send data from JS via JSON
var pricesum = sumprice;
var date = expirationdates;
var price = prices;
$.ajax({
type: "POST",
url: "print",
data: {
'pricesum': pricesum, 'date': date,'price': price,
},
They have the following form
expirationdate = request.POST.get('date', False);
price =request.POST.get('price', False);
print(expirationdate)
print(price)
Next, I get them in the django function, but I always get false. How do I get them correctly so that they are all in the array?
I'm trying
expirationdate = request.POST.get('date[]', False);
price =request.POST.get('price[]', False);
But I get only the last element of the array date and price
[('pricesum', '3600'), ('date[]', '2021-05-06'), ('price[]', '900')]
After some discussions, it seems that you should stringify your data in your ajax post request.
$.ajax({
type: "POST",
url: "print",
data: JSON.stringify({
'pricesum': pricesum, 'date': date,'price': price,
})
})
Then you can access the data posted by loading the stringified JON into your Python code :
import json
post_data = json.loads(request.body)
pricesum = post_data.get("pricesum", False)
date = post_data.get("date", False)
price = post_data.get("price", False)
I have a JSON data loaded from database using AJAX, it has name and value pair after serializing using JavaScriptSerializer, but I need to use it without the names, only the values is needed, how can I serialize the same data without the names
AJAX CALL
$.ajax({
url: 'RhemaServices.asmx/GetMapData',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset-utf-8",
success: function (data) {
},
error: function (err) {
console.log(err)
},
complete: function () {
}
});
JSON data returned
[{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}]
I need to re-serialize this data to get the below maybe looping through the data to read only the values
[{"af":"16.63","al":"11.58","ve":"285.21","vn":"101.99"}]
This is what I am trying to do with the AJAX JSON data, but its not working
var datas = [];
data.map(function (item) {
var newdata = item.Code + ":" + item.Total;
datas.push({ newdata });
})
Since your requested data is an object, I suggest you use forEach instead of map and create your properties as such:
let data = [{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}];
var datas = {};
data.forEach(item => datas[item.Code] = item.Total);
console.log(datas);
// {"af":16.63,"al":11.58,"ve":285.21,"vn":101.99}
Is data coming all together as a single string? Then it's as simple as
var datas;
...
success: function (data) {
datas = JSON.parse(data);
}
Not sure what you mean by trim off the name ,only values - but you can do with the JavaScript object whatever you want
How do i get list items from different lists in SharePoint using javascript. Given that all my list are stored in an array. And I need to loop through the array and execute similar functions on each list.
function initializePage() {
listcollections.forEach(function (value, index) { // listcollections is the array that contains the list url for different lists
var listtitle = value.listTitle;
var siteUrl = value.siteURL;
getItemsWithCaml(siteUrl, listtitle,
function (camlItems) {
var listItemEnumerator = camlItems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var EventsItem = new Events();
var listItem = listItemEnumerator.get_current();
EventsItem.eventTitle = listItem.get_item('Title');
EventsItem.eventDate = listItem.get_item('EventDate');
EventsItem.eventId = listItem.get_id();
EventsItem.eventSite = siteUrl;
EventsItem.eventList = listtitle;
EventsCollection.push(EventsItem);
}
},
function (sender, args) {
alert('An error occurred while retrieving list items:' + args.get_message());
});
})
};
function getItemsWithCaml(siteUrl, listtitle, header, success, error)
{
var hostWebContext = new SP.ClientContext(siteUrl);
var list = hostWebContext.get_web().get_lists().getByTitle(listtitle);
var caml = new SP.CamlQuery();
//Create the CAML that will return only items expiring today or later
caml.set_viewXml("<View><Query><Where><Geq><FieldRef Name=\'Expires\'/><Value Type=\'DateTime\'><Today /></Value></Geq></Where> </Query></View>");
var camlItems = list.getItems(caml);
hostWebContext.load(camlItems);
hostWebContext.executeQueryAsync(
function () {
success(camlItems);
},
error
);
};
//need to execute certain functions to format each list item
// I am not able to retrieve all list items in a single variable to be able to display data from all lists together
In the example below, I create a JavaScript object named ListDataCollection that contain a property Lists that is an array of objects.
Each of those contain a Url property whit the url of the lists I want to get the content.
Then I loop trough the array of objects and call the Sharepoint REST api for each Url.
Each time a call is complete :
I create a Data property on the current object with the data received
by the ajax call to the REST api.
I also update the current object Completed property to true.
Then I call a function named ifAllCompleted that check if all ajax calls are ended.
When all data is received, I log the word Completed on the browser console.
At this point, you have an array of objects. Each object contains the data of one Sharepoint list.
For example :
ListDataCollection.Lists[0].Data.d.results[0].Title
will contain the value of the Title Column of the first element in the first list.
If you want, you can merge all data in one array using the concat function in JavaScript.
Look at the 4 lines of code following the word Completed.
Hope this can help!
<script>
var ListDataCollection = {
Lists:[{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List1')/Items",
Completed:false
},{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List2')/Items",
Completed:false
},{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List3')/Items",
Completed:false
}]
};
function ifAllCompleted() {
for (var i=0;i<ListDataCollection.Lists.length;i++) {
if (!ListDataCollection.Lists[i].Completed) {
return false;
}
}
console.log('Completed');
var arrayOfAllData = ListDataCollection.Lists[0].Data.d.results;
arrayOfAllData = arrayOfAllData.concat(ListDataCollection.Lists[1].Data.d.results);
arrayOfAllData = arrayOfAllData.concat(ListDataCollection.Lists[2].Data.d.results);
console.log('Total elements : ' + arrayOfAllData.length);
}
$(document).ready(function(){
for (var x=0;x<ListDataCollection.Lists.length;x++) {
$.ajax({
url:ListDataCollection.Lists[x].Url,
indexValue:x,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data, status, xhr) {
ListDataCollection.Lists[this.indexValue].Data = data;
ListDataCollection.Lists[this.indexValue].Completed = true;
ifAllCompleted();
},
error: function (xhr, status, error) {
console.log('error');
}
});
}
});
</script>
i'm having a minor issue. I'm using REST/JS to populate a dropdown box, which requires first getting the lookup of a column in a list.
//Product Model Cascade
document.getElementById("productDD").onchange = function() {
var prod = this.options[document.getElementById("productDD").selectedIndex].text;
var select = document.getElementById("productModelDD");
$(select).empty();
var call2 = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/Items", //the list
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call2.done(function(data, textStatus, jqXHR) {
var select = document.getElementById("productModellDD");
for (index in data.d.results) {
var parent = data.d.results[index].AT_ARMATECproducts; //Lookup column
console.log("parent var: " + parent);
if (parent == prod) {
var op = document.createElement("option");
op.text = data.d.results[index].Title;
op.value = data.d.results[index].Title;
select.appendChild(op);
}
}
});
}
but the parent value is coming back as "undefined" and i've triple checked that this is the correct list. I've also tried .get_LookupValue() but it comes back as can't get it from an undefined field.
So how do you get the value of a lookup field via rest?
EDIT:
I have done select/expand in the REST Query but have come up with a 400 bad request error:
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/items?$select=Title,AT_ARMATECproducts/Title&$expand=AT_ARMATECproducts/Title",
Where AT_ARMATECproducts is the lookup field in the ARMATEC Product Models List. AT_ARMATECproducts is a lookup to the ARMATEC Products list which grabs the titles.
So, it turns out the lookup list was under a different name for some reason, it the list it shows up as AT_ARMATECproducts but seems to actually be AT_Products1.
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/items?$select=Title,AT_Products1/Title&$expand=AT_Products1/Title",
var parent = data.d.results[index].AT_Products1;
now returns [object object], when I tried .Titles it returned with the Titles of the List not the lookup list. And when I tried .AT_Products1.Title it returned with undefined.
When working with User/Lookup field values via SharePoint REST API it is important to differentiate between single-valued and multi-valued lookup fields.
Single-valued lookup fields
Assume Employee list with a single-valued lookup field Department
Then the query: /_api/web/lists/getbytitle('<list title>')/items returns lookup Id, for example:
getListItems(_spPageContextInfo.webAbsoluteUrl,'','Employees',
function(items){
if(items.length > 0)
console.log(items[0].DepartmentId); //returns LookupId
},
function(error){
console.log(error.responseText);
});
The query:
/_api/web/lists/getbytitle('Employees')/items?$select=Department/Title,Department/Id&$expand=Department
returns projected Department object as shown below:
getListItems(_spPageContextInfo.webAbsoluteUrl,'?$select=Department/Title,Department/Id&$expand=Department','Employees',
function(items){
if(items.length > 0)
console.log(items[0].Department.Title);
console.log(items[0].Department.Id);
},
function(error){
console.log(error.responseText);
});
Multi-valued lookup fields
Assume Employee list with a multi-valued lookup field Departments
Then the query: /_api/web/lists/getbytitle('<list title>')/items returns an array of lookup ids, for example:
getListItems(_spPageContextInfo.webAbsoluteUrl,'','Employees',
function(items){
if(items.length > 0)
console.log(items[0].DepartmentsId); //returns an array [LookupId1, LookupId1 .. LookupIdN]
},
function(error){
console.log(error.responseText);
});
The query:
/_api/web/lists/getbytitle('Employees')/items?$select=Departments/Title,Departments/Id&$expand=Departments
returns projected Departments array of objects as shown below:
getListItems(_spPageContextInfo.webAbsoluteUrl,'?$select=Departments/Title,Departments/Id&$expand=Departments','Employees',
function(items){
if(items.length > 0)
if(items[0].Departments.results.length > 0) {
console.log(items[0].Departments.results[0].Title);
console.log(items[0].Departments.results[0].Id);
}
},
function(error){
console.log(error.responseText);
});
SharePoint 2013 REST read operation function:
function getListItems(url, query, listName, success, failure) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d.results);
},
error: function (data) {
failure(data);
}
});
}
Try
/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/items?$select=Title,AT_ARMATECproducts/Title&$expand=AT_ARMATECproducts"
as you endpoint
The expand query should only contain the title of the lookup column, and should not include the lookup field. Your select is fine, but the expand isn't.
below query finally worked for me
Merged is a calculated field in Cats list
Cat is a lookup field(which looks above Merged column) in the MainFlat list
"?$select=Title,number,Cat/Merged&$expand=Cat" +
"&$filter=Cat/Merged eq '"+Merged+"' "
https://sharepoint.stackexchange.com/a/152997/16880
I am having an issue where my collection property (in this case Parameters Collection) in my model is not being included in the JSON string created by the JSON.stringify function. Is there any reason why this might be happening? It basically just excludes it and adds the rest of the variables to the JSON string.
Here is the event:
EventAggregator.on('toggleFacet', function (facets) {
var facets = SearchOptionsUtil.getCheckedFacets(facets);
var sortOptions = SearchOptionsUtil.getSortOptions();
var searchOptions = new SearchOptionsModel();
for(var facet in facets){
var id = facet;
var value = facets[facet];
searchOptions.parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
var criteria = $.extend(facets, sortOptions);
location.hash = UriUtil.getUriHash(criteria);
RequestUtil.requestSearchResults(searchOptions);
});
Here is the fetch:
requestSearchResults: function (searchOptions) {
//fetch the results
var performSearchModel = new PerformSearchModel();
var searchOptionsJson = JSON.stringify(searchOptions);
performSearchModel.fetch({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({searchOptionsJson: searchOptionsJson}),
success: function (response) {
console.log("Inside success");
console.log(response);
},
error: function (errorResponse) {
console.log("Inside Failure")
console.log(errorResponse.responseText)
}
}) //have to wait for the fetch to complete
.complete(function () {
//show our regions
App.facetsRegion.show(new FacetListView({collection: performSearchModel.facets}));
App.resultsRegion.show(new ResultListView({collection: performSearchModel.results}));
//perform search fetch complete
});
}
and here is the model:
var SearchOptionsModel = Backbone.Model.extend({
defaults: {
parameters: ParameterCollection,
currentItemId: '{EE8AA76E-0A3E-437B-84D8-AD7FCBAF2928}',
sortBy: 0,
sortDirection: 'asc',
resultsPerPage: 10
},
initialize: function () {
this.parameters = new ParameterCollection();
//fetch calls an on change event.
this.on("change", this.fetchCollections);
},
url: function () {
return '/Services/Search/SearchService.asmx/SearchOptions';
},
parse: function (response) {
var data = JSON.parse(response.d);
return data;
},
fetchCollections: function () {
//when we call fetch for the model we want to fill its collections
this.parameters.set(
_(this.get("parameters")).map(function (parameter) {
return new ParameterModel(parameter);
})
);
}
});
UPDATE**
So I changed the way I create and add the parameters collection in the SearchOptionsModel and the JSON object is being formed correctly. I changed it from this:
var searchOptions = new SearchOptionsModel();
for(var facet in facets){
var id = facet;
var value = facets[facet];
searchOptions.parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
To this:
var parameters = new ParameterCollection();
//loop through all of the variables in this object
for(var facet in facets){
var id = facet;
var value = facets[facet];
parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
var searchOptions = new SearchOptionsModel({parameters: parameters});
Now the parameters are filled under the attributes in the model and I see an empty parameters variable on the searchOptions object (which was being filled before instead). Why is there a parameters variable set in the SearchOptionsModel if I am not explicitly creating it? Is it because the parameters default is set to a collection?
To convert a Backbone model to JSON, you must use the toJSON method:
model.toJSON();
Check doc here: http://backbonejs.org/#Model-toJSON