I' trying to send some data from the frontend to a Controller in Spring. I am able to recover all the data except for the Integer [] objectIds.
This is my ajax function:
var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });
$.ajax({
type:'POST',
url:'/sendData',
data:{'start':start, 'end':end, 'locale':locale, dataToSend},
async:false,
dataType: "json",
success:function(data){}
});
And this is my Controller function:
#PostMapping(path="/sendData")
public #ResponseBody String sendData(HttpServletResponse response,
#RequestParam(required=true, name="start") String start,
#RequestParam(required=true, name="end") String end,
#RequestParam(required=true, name="locale") Locale locale,
#RequestParam(required=false, name="objectIds") Integer[] objectIds) throws DocumentException, IOException {
//some more code
}
any idea why it's not working??
Problem is in the way you are sending JSON
Case 1: How you are sending
var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });
var mainJSOn = {
'start': "start",
'end': "end",
'locale': "locale",
dataToSend
}
console.log(JSON.stringify(mainJSOn));
OUTPUT:
{"start":"start","end":"end","locale":"locale","dataToSend":"{\"objectIds\":[{\"objectIds\":111},{\"objectIds\":222}]}"}
Case 2: How you should actually send
var dataToSend1 = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend1 = JSON.stringify(dataToSend1 );
var mainJSOn1 = {
'start': "start",
'end': "end",
'locale': "locale",
'objectIds': dataToSend1
}
console.log(JSON.stringify(mainJSOn1));
OUTPUT:
{"start":"start","end":"end","locale":"locale","objectIds":"[{\"objectIds\":111},{\"objectIds\":222}]"}
Look at the Output of Both Cases.
Change your code like done in Case 2
Working Fiddle
Your are stringifying the wrong object and burying the key objectIds inside it
Try changing to
var dataToSend = JSON.stringify([{objectIds: 111}, {objectIds: 222}]);
$.ajax({
type: 'POST',
url: '/sendData',
data: {
'start': start,
'end': end,
'locale': locale,
'objectIds': dataToSend
},
// async:false, // NEVER USE THIS!!!!
dataType: "json",
success: function(data) {}
});
Related
Currently I'm trying to call a function with a data response from an ajax call, and I'm getting that my constant stores is not iterable. My AJAX call looks like this
jQuery.ajax({
type: 'GET',
url: "<?php echo JURI::base() . "index.php?option=com_ajax&module=hunter_maps_dev&method=getStoresByZip&zip="?>" +zip+ "&format=json",
datatype : "application/json",
success:function(data){
console.log('success');
const stores = data;
console.log(stores);
buildLocationList(stores);
},
...
function buildLocationList({ features }) {
for (const { properties } of features) {
}
}
and I'm logging it to the console.
I'm getting this for the data in the console: data: "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.9981929\",\"39.7164275\"]},\"properties\":{\"store
and this is the mock I was previously using:
const stores = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.034084142948, 38.909671288923]
},
'properties': {
'storeImage' : 'https://via.placeholder.com/150',
'storeName' : 'Test Store',
'phoneFormatted': '(202) 234-7777',
'phone': '2022347336',
'address': '1471 P St NW',
'city': 'Washington DC',
'country': 'United States',
'crossStreet': 'at 15th St NW',
'postalCode': '20005',
'state': 'D.C.'
}
},
]
};
What is missing for me to get this to match the mock format so that it's iterable?
UPDATE: Full response currently
{"success":true,"message":null,"messages":null,"data":"{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.9981929\",\"39.7164275\"]},\"properties\":{\"storeImage\":\"1542820219karmalogo2-Copy.png\",\"storeName\":\"Karmaceuticals\",\"phoneFormatted\":\"303-765-2762\",\"address\":\"4 S Santa Fe Drive\",\"city\":\"Denver\",\"country\":\"USA\",\"postalCode\":\"80223\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.8526653\",\"39.7861717\"]},\"properties\":{\"storeImage\":\"1438052652medicineman_logo_web.jpg\",\"storeName\":\"Medicine Man - Denver\",\"phoneFormatted\":\"303-373-0752\",\"address\":\"4750 Nome St.\",\"city\":\"Denver\",\"country\":\"Denver\",\"postalCode\":\"80239\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-105.0135439\",\"39.7206576\"]},\"properties\":{\"storeImage\":\"1455044497CannaBoticaOrange.png\",\"storeName\":\"CannaBotica \",\"phoneFormatted\":\"303-777-1550\",\"address\":\"219 Vallejo st.\",\"city\":\"Denver\",\"country\":\"United States\",\"postalCode\":\"80223\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.8664385\",\"39.6817321\"]},\"properties\":{\"storeImage\":\"1458987858medicine-man-aurora.jpg\",\"storeName\":\"Medicine Man - Aurora\",\"phoneFormatted\":\"303-923-3825\",\"address\":\"1901 S Havana Street\",\"city\":\"Aurora\",\"country\":\"\",\"postalCode\":\"80014\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-116.905029\",\"33.0433045\"]},\"properties\":{\"storeImage\":\"1479714765showgrow-logo.jpg\",\"storeName\":\"Showgrow - Ramona\",\"phoneFormatted\":\"760-687-9700\",\"address\":\"736 Montecito Way\",\"city\":\"Ramona\",\"country\":\"United States\",\"postalCode\":\"92065\",\"state\":\"California\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-117.8467455\",\"33.7201192\"]},\"properties\":{\"storeImage\":\"1479715612showgrow-logo.jpg\",\"storeName\":\"Showgrow -Santa Ana\",\"phoneFormatted\":\"949-565-4769\",\"address\":\"1625 E St Gertrude Pl\",\"city\":\"Santa Ana\",\"country\":\"United States\",\"postalCode\":\"92705\",\"state\":\"California\"}}]}"}
You need to parse the JSON string to convert it to an object:
buildLocationList(JSON.parse(stores));
i have a form on select from dropdown the request goes to the controller and returns the following in
JSON formate
[{id: 2, slug: "manager", name: "Assistant Manager", created_at: "2019-12-10 09:20:45",…}]
0: {id: 2, slug: "manager", name: "Assistant Manager", created_at: "2019-12-10 09:20:45",…}
created_at: "2019-12-10 09:20:45"
id: 2
name: "Assistant Manager"
permissions: [{id: 2, slug: "edit-users", name: "Edit Users", created_at: "2019-12-10 09:21:01",…}]
0: {id: 2, slug: "edit-users", name: "Edit Users", created_at: "2019-12-10 09:21:01",…}
slug: "manager"
updated_at: "2019-12-10 09:20:45"
now i want to iterate from permissions and show name in another drop-down with multiple selection buit i don't know how to iterate from this JSON i tried the following script but doesn't work
$(document).ready(function () {
$("#roles").on('change', function () {
var query = $(this).val();
// alert(query);
if (query != '') {
$.ajax({
url: "{{route('get-roles-ajax-call')}}",
method: "POST",
dataType: 'JSON',
data: {"_token": "{{ csrf_token() }}", query: query},
success: function (data) {
var values = $.parseJSON(data)
$(values).each(function(i,val){
$.each(val,function(key,val)
{
console.log(key + " : " + val);
});
});
}
});
}
return false;
});
});
When setting this line dataType: 'JSON' you are already telling the $.ajax function to return JSON.
Quoted from jQuery documentation of $.ajax
"json": Evaluates the response as JSON and returns a JavaScript object.
So there is no need to parse the data once you've received it. Is is already JSON.
Now loop through every object in the data to search for the permissions property. If the object has the permissions property and the value of that is an array that is not empty then loop over each object in the permissions array and look for the the name property on each permission.
$.each(data, function(i, entry) {
var permissions = entry.hasOwnProperty('permissions');
if (permissions && permissions.length) {
$.each(entry.permissions, function(j, permission) {
console.log(permission.name);
});
}
});
Though I would suggest that you modify the, or create a new, server response so that all this filter work is done server side and you only have to call the server to get the data you need.
I bring data into json string which comes as r.d in my below code.
Now I want to access the field of it. so how should I access it ?
Here is the code
$.ajax({
url: "GET_DATA_BY_STORE.aspx/GETSTOREINFO",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ STORE_ID: STORE_ID }),
async: true,
processData: false,
cache: false,
success: function (r) {
alert(getJSONValue[0].STORE_ID);
},
error: function (xhr) {
// alert('Error while selecting list..!!');
}
})
And in r.d I get data as
Once you have converted it as json object using JSON.parse you can access properties like you normally do with javascript objects:
var jsonString = '{"d": [{"field1": "value1", "field2": 15.0}, {"field3": [1,2,3]}]}'
var r = JSON.parse(jsonString)
console.log(r.d)
// output: [ { field1: 'value1', field2: 15 }, { field3: [ 1, 2, 3 ] } ]
console.log(r.d[0].field1)
// output: value1
console.log(r.d[0].field2)
// output: 15
console.log(r.d[1].field3)
// output: [ 1, 2, 3 ]
// you can also use brackets notation to access properties in object
console.log(r.d[0]["field1"])
// output: value1
// or you can iterate properties if the data type of a field is an array (r.d is an array)
r.d.forEach(function(prop) {
console.log(prop);
})
// output: { field1: 'value1', field2: 15 }
// { field3: [ 1, 2, 3 ] }
normaly I would write
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: {id: 1},
async: false,
type: "POST"
})
when I want to pass the integer id to server side in C#:
public void PlantHistoryContent(int id)
{
///
}
How to do the same with a list of integer?
So I have a object-list of unkown length and want to pass it as a list to server side?
My server side should be
public void PlantHistoryContent(List<int> id)
{
///
}
How to write the ajax call data parameter to this?
A list in JavaScript looks like:
var list = [ 1, 2, 3, 4 ];
To build it you can do:
var list = [];
list.push(1);
list.push(2);
list.push(3);
list.push(4);
Then when you send it you can do:
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: { ids: list },
async: false,
type: "POST"
})
or
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: { ids: [ 1, 2, 3, 4 ] },
async: false,
type: "POST"
})
By default form-encoding is used. The request body will look like:
ids[0]=1&ids[1]=2&ids[2]=2&ids[3]=3
With form-encoding there is no way to know what the type of the parameter is. They're all strings.
If you use JSON as your transfer encoding instead you can send integers because JSON knows string and ints and list etc.
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: { data: JSON.stringify({ ids: [ 1, 2, 3, 4 ] }) },
async: false,
type: "POST"
})
Now your request body looks like:
data=%5B1%2C2%2C3%2C4%5D
I am trying to create a real-time filter on a table using knockoutjs.
I have managed to get everything to work when I statically create the observable array like this:
$(function() {
var assets = [
{id: "1", poster: "Pic010.jpg", name: "Asset1", category: "category1", type: "Movie", popup: "1" },
{id: "2", poster: "Pic06.jpg", name: "Asset2", category: "category2", type: "Movie", popup: "2" },
{id: "3", poster: "Pic04.jpg", name: "Asset3", category: "category1", type: "Pop-up", popup: "3" },
{id: "4", poster: "Pic07.jpg", name: "Asset4", category: "category2", type: "Pop-up", popup: "4" },
{id: "5", poster: "Pic011.jpg", name: "Asset1", category: "category3", type: "Promo", popup: "5" }
];
var viewModel = {
assets: ko.observableArray(assets),
query: ko.observable(''),
search: function(value) {
viewModel.assets.removeAll();
for(var x in assets) {
if(assets[x].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
viewModel.assets.push(assets[x]);
}
}
}
};
viewModel.query.subscribe(viewModel.search);
ko.applyBindings(viewModel);
});
JSFiddle of working code: http://jsfiddle.net/7ZLdk/1/
Now when I try to load the observable array data via ajax like this:
var assets = [];
$.ajax({
url: '/Assets/getJson/',
type: "GET",
dataType: 'json',
success: function (data) {
console.log(data);
viewModel.assets(data);
}
});
the data is displayed correctly in the table when the page is loaded, but when I start typing in the search input, all the data disappears.
I would appreciate it if someone could explain what I am doing incorrectly in the AJAX load? TIA
You are better off creating a ViewModel function, so the viewmodel only accesses data within itself:
$(function() {
$.ajax({
url: '/Assets/getJson/',
type: "GET",
dataType: 'json',
contentType: "application/json",
success: function (data) {
console.log(data);
var viewModel = new ViewModel(data);
ko.applyBindings(viewModel);
}
});
});
function ViewModel(assets) {
var self = this;
self.assets = ko.observableArray(assets);
self.allAssets = assets;
self.query = ko.observable('');
self.search = function(value) {
self.assets.removeAll();
for(var x in self.allAssets) {
if(self.allAssets[x].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
self.assets.push(self.allAssets[x]);
}
}
};
self.query.subscribe(self.search);
}
I have resolved the problem.
I was not populating the assets array. This is the updated ajax call:
$.ajax({
url: '/Assets/getJson/',
type: "GET",
dataType: 'json',
contentType: "application/json",
success: function (data) {
console.log(data);
viewModel.assets(data);
assets = data; // THIS WAS MISSING
}
});