I am providing data over REST to a custom HTML form with a SELECT 2 inside it. However I am not able to map the data from REST to the SELECT 2!
javascript for my select2:
$("#space-select").select2({
width : '100%',
ajax : {
delay: 500,
url : url,
type : 'GET',
contentType : 'json',
processResults : function(data) {
return {
results : $.map(data.spaces, function(space) {
return {
id: space,
text: space,
};
})
};
}
}
});
incoming xml:
<configuration>
<spaces>
<space>Space 1</space>
<space>Space 2</space>
<space>Space 3</space>
</spaces>
</configuration>
I dont really understand why the data is not mapped correctly!
SOLUTION:
I found the wrong part in my Code:
i used:
contentType : 'json',
but you have to use:
dataType : 'json',
Related
I am trying ajax Javascript Map, to spring controller. but it's getting null in backend. Please excuse if i am repeating question.
I can't change Map type, as my whole front end logic on it. Because set, get and has method from Map is what I need.
var ansMap = new Map(); // This way i created object
// added many values in ansMap,
$.ajax({
type: "POST",
url: myUrl,
contentType : 'application/json',
//cache: false,
dataType : 'json',
data : ansMap, // can't JSON.stringy(ansMap) as it gives empty json
success: function(result) {
console.log(result);
},
Spring code
#RequestMapping (value="myUrl", method=RequestMethod.POST)
public #ResponseBody String saveData(#RequestParam(required = false, value = "mapData") Map<String,List<String>> mapData, Model map)
{
log.info("Call Success");
log.info("mapData: "+mapData);
Please suggest what needs to be done here.
You can actually send your Map without mutating the value
var ansMap = new Map(); // This way i created object
// added many values in ansMap,
$.ajax({
type: "POST",
url: myUrl,
contentType : 'application/json',
//cache: false,
dataType : 'json',
data : JSON.stringify(Object.fromEntries(ansMap)), // can't JSON.stringy(ansMap) as it gives empty json
success: function(result) {
console.log(result);
},
That will turn it into a javascript object.
Object.fromEntries Will turn you Map into a javascript object, without altering the original Map
Regarding your backend i think you mis-interpret the #RequestParam annotation
The #RequestParam is to extract query parameters, form parameters and even files from the request.
I think that what you are looking for is #RequestBody.
Meaning you would be looking for something similar to :
#RequestMapping(value="/myUrl",method = RequestMethod.POST)
public String saveData( #RequestBody Map<String,Object> body) {
This should work
page
<button id="doPost"> post </button>
<script>
$(function () {
var map = new Map();
map.set('CIQ_2','aa');
map.set('CIQ_3','78965412300');
console.log(map);
$("#doPost").click (function() {
var settings = {
beforeSend: function(xhr, options) {
xhr.setRequestHeader("content-type" ,"application/json; charset=utf-8");
},
type: 'POST',
url: '/post' ,
data: JSON.stringify(Object.fromEntries(map))
}
$.ajax(settings).done(function(result) {
console.log("done : " + result);
});
});
});
</script>
Controller
#PostMapping("/post")
#ResponseBody
public String post(#RequestBody Map<String,String> data) {
System.out.println(data);
return "data well received";
}
will print
{CIQ_2=aa, CIQ_3=78965412300}
working code on GitHub
I have a an extjs 4.2 combobox that I'm using to display some data. Now I'm trying that based on a condition the combo would display a default value. I managed to return the needed data based on that condition, however I'm failing to set the necessary value in the combobox. How am I supposed to set that specific value?
combo:
var locationStore = Ext.create('Ext.data.Store', {
model: 'model_LOCATION',
proxy: {
type: 'ajax',
url: 'Record?DB=GEO&Table=LOCATION',
reader: {
type: 'xml',
record:'record'
}
},
autoLoad:true
});
var C_LOCATION= Ext.create('Ext.form.ComboBox', {
name : 'C_LOCATION',
id : '${DB}.${Table}.C_LOCATION',
store : locationStore,
queryMode : 'local',
displayField : 'display',
valueField : 'value',
});
AJAX call:
var data;
var code = 111;
data = "CODE ='" + code + "'";
var text;
$.ajax({
type: "POST",
url: "Record?DB=GEO&Table=LOCATION",
dataType: 'xml',
data: {
"Where": data
},
success: function(xml) {
text = xml;
Ext.getCmp('${DB}.GEO.LOCATION').setValue(text);
}
});
Give the combo box a reference in the config section (reference: 'comboBox'). Then call comboBox.setValue(defaultValueGoesHere) in your function where you are getting the specific value. You may need to hunt down the comboBox reference depending where you are.
I guess you will have to parse your XML response. Similar as in your code definition for the locationStore, where you specify the record in the xml response.
Why do you make the second ajax call?
Could you not filter the locationStore based on the CODE value, instead?
I am using tagit plugin (https://github.com/aehlke/tag-it "Tagit Plugin aehlke") and auto-complete feature. I have to change tags based on the selection made using the auto-complete feature.
It worked for the first selection but not for the second one .
I removed the existing tags - using 'removeAll" in tagit plugin and did tagit() - doesn't work ??
This is my code :
<script>
$(document).ready(function() {
var allKeyWordsString=" ";
$.ajax({
url : some url,
type : 'GET',
//data : "query="+$("#query").val(),
async : false,
cache : false,
contentType : "application/x-www-form-urlencoded",
processData : false,
success : function(returndata) {
allKeyWordsString = returndata.success;
alert("keywords are "+ allKeyWordsString);
}
});
var sampleTags = allKeyWordsString.split(',');
$("#keyWordForm").autocomplete({
source: sampleTags,
minLength : 3,
select: function(event,ui){
var selectedKeyWord = ui.item.value;
var services = " ";
$.ajax({
url : 'some url',
type : 'GET',
data : "query="+selectedKeyWord+" services",
async : false,
cache : false,
contentType : "application/x-www-form-urlencoded",
processData : false,
success : function(returndata) {
services = returndata.success;
alert(" ajax call response is "+services);
}
});
if ($('#servicesForm').val().length != 0){
$('#servicesForm').tagit('removeAll');
}
document.getElementById("servicesForm").value=services;
$('#servicesForm').tagit();
}
});
return false;
});
</script>
Please help
To add tag, you can use method createTag:
$("#myTags").tagit("createTag", "brand-new-tag");
Similarly, method removeTagByLabel is for removing a tag:
$("#myTags").tagit("removeTagByLabel", "my-tag");
You can find above methods in the documentation: https://github.com/aehlke/tag-it/blob/master/README.markdown
I have a very specific problem: I have a small form with four options. You may fill them out or not, and when you click 'Ok', I load a jqGrid with data depending on those options. But since I do not know what my columns look like, I let my servlet generate the column model and column name; thus I have to make an AJAX request to load the data and then fill it in jqGrid as "local" data. I would like to use pagination though.
Thus my question: How may I load more data into a jqGrid after it is already established through local data?
here's the code:
$.ajax({
type : 'GET',
url : 'data.jsp',
data : reqData,
dataType : 'json',
error: function() {
$("#dialog-message").dialog("open");
$("#ajax-loader").css("display", "none");
},
success : function(result) {
jQuery("#results").jqGrid({
data : result.rows,
datatype : "local",
colNames : result.columnNames,
colModel : result.columnModel,
pager : $('#pager'),
rowNum : 1000,
scroll : true,
viewrecords : true,
sortname : 'TITEL',
width : window.innerWidth - 30,
height : window.innerHeight - 190,
altRows : true,
loadError: function() {
$("#dialog-message").dialog("open");
$("#ajax-loader").css("display", "none");
},
loadComplete: function() {
$("#ajax-loader").css("display", "none");
}
}).jqGrid("navGrid", "#pager", {
edit: false,
add: false,
del: false,
search: true,
refresh: false
}).jqGrid("gridResize");
}
});
/edit: I've tried to do the following, but that still doesn't solve the problem that the grid doesn't know how many total pages there actually are (actually, at that point, I don't even know), and also, after loading, it thinks it only gets local data. Is there maybe an onScroll event or something? I haven't found one.
datatype : !json ? "local" : function(postdata) {
$.ajax({
type: 'GET',
url: 'data.jsp',
data: $.merge(postdata, reqData),
dataType: 'json',
success: function(data, status, jqXHR) {
var mygrid = jQuery("#results")[0];
var myjsongrid = eval("("+jqXHR.responseText+")");
mygrid.addJSONData(myjsongrid);
}
});
},
Can you not do something like this...get the grid, clear the data, define the url to get the data from (it may change depending on what option your user selected) and then change the dataformat to json instead of local.
var grid = $('#TargetGridID');
grid.clearGridData();
grid.setGridParam({ url: '../controller/action?datatype=Option1' });
grid.setGridParam({ datatype: 'json' });
grid.trigger('reloadGrid');
We use this methodology and it works great...use this with stored procedures capable of paging and the grids are blazing fast! I know a 20,000 row grid takes us roughly 700ms with a page count of 500 rows.
If you are using SQL for your data I can upload a sample on how to support paging in a SQL Stored Proc, very useful stuff.
How to disable autoload in jqGrid and load data manually when I need it?
Thanks.
If you set datatype to 'local' the data from the server will be not loaded. To force the loading of data you can change datatype to 'json' or 'xml' with respect of setGridParam method (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options and http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods#grid_related_methods) and then call trigger("reloadGrid") method.
See jqGrid is not loading data which has also the information what you asked.
Just don't set the default URL in the table. And install it just when you need to load data (for example by pressing a button) and then .trigger("reloadGrid").
Example for you:
jQuery("#grid").jqGrid(
{
//Simply comment out the URL
//url :"salepointsprovider.php",
datatype:"json",
colModel :[
{name:'SalePointId', index:'SalePointId'},
{name:'Name', index:'Name'}
]
}
$('#ShowRecordsButton').click(function () {
jQuery("#grid").jqGrid('setGridParam',
{url:"salepointprovider.php?SalePointId=" + argSalePointId, page:1});
jQuery("#grid").trigger('reloadGrid');
}
My grid without url send requests to server:
.../?_search=false&nd=1370817124473&rows=20&page=1&sidx=&sord=asc
Set datatype: "local" solve problem.
Reload grid by
`function reloadGrid(gridId, gridData){
$(gridId).jqGrid('clearGridData'); // need for nonempty grig (see http://www.trirand.com/blog/?page_id=393/help/triggerreloadgrid-not-work/)
$(gridId).jqGrid('setGridParam', {data: gridData}).trigger('reloadGrid');
}
`
No need to change datatype (at least for my json case it is recognized)
In treegrid you couldn't use datatype = 'local'. So instead 'local', I set datatype = 'jsonstring', define empty fake data and jsonReader. jsonReader should be defined correctly according to your retrieved data. Thanks for Oleg's answer. And, when I need to load data, I simply change datatype to 'json'.
var fakeData ={
rows: []
};
...
datatype: 'jsonstring',
datastr: fakeData,
...
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.rows; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}