I found that we can load the jqGird with JSON string.
Please refer to map JSON data to jqGrid.
Is it possible to use this feature with sjg:grid tag?
I look at tag attribute and only find that the data can be loaded from a URL which will call a Struts action and that action returns a JSON data, but in my program I already have the JSON value and need to pass it to jqGird.
If the tag does not support data, what is the best way to use jqGrid which are included in Struts 2 jQuery plugin.
Set the dataType="local" to the sjg:grid and remove href attribute. Then provide row data from the array. For example
<sjg:grid
id="gridtable"
caption="Example (Editable/Multiselect)"
dataType="local"
pager="true"
navigator="true"
navigatorSearchOptions="{sopt:['eq','ne','lt','gt']}"
navigatorAddOptions="{height:280, width:500, reloadAfterSubmit:true}"
navigatorEditOptions="{height:280, width:500, reloadAfterSubmit:false}"
navigatorEdit="true"
navigatorView="true"
navigatorViewOptions="{height:280, width:500}"
navigatorDelete="true"
navigatorDeleteOptions="{height:280, width:500,reloadAfterSubmit:true}"
gridModel="gridModel"
rowList="5,10,15"
rowNum="5"
rownumbers="true"
editurl="%{editurl}"
editinline="true"
multiselect="true"
onSelectRowTopics="rowselect"
>
<sjg:gridColumn name="id" index="id" title="Id" formatter="integer" editable="false" sortable="true" search="true" sorttype="integer" searchoptions="{sopt:['eq','ne','lt','gt']}"/>
<sjg:gridColumn name="name" index="name" key="true" title="Country Name" editable="true" edittype="text" sortable="true" search="true" sorttype="text"/>
</sjg:grid>
<script type="text/javascript">
$(document).ready(function(){
var mydata = [{id:"1",name:"Roman C"}];
//for(var i=0;i<=mydata.length;i++) $("#gridtable").jqGrid('addRowData',i+1,mydata[i]);
$("#gridtable").jqGrid('setGridParam', {
data: mydata
}).trigger("reloadGrid");
});
</script>
The above code works perfect, it add rows for each grid load. If u want new data every time u can use this:
var allParameters = $("#gridtable").jqGrid("getGridParam");
allParameters.data = myData;
$("#gridtable").trigger('reloadGrid');
Instead of:
$("#gridtable").jqGrid('setGridParam', {
data: mydata
}).trigger("reloadGrid");
Also if u want to make an ajax call to action and fetch list and parse it to add to myData. Check this:
$.ajax({
url: "myAction.action", cache: false, dataType: 'json', data: "employeeId=" +
employeeIdList,
success: function (data) {
var jsonData = JSON.stringify(data.jsonResponse);
var parsedData = JSON.parse(jsonData);
if (parsedData.hasResults) {
var myData = parsedData.jsonResults;
$(document).ready(function () {
var allParameters = $("#gridtable").jqGrid("getGridParam");
allParameters.data = myData;
$("#gridtable").trigger('reloadGrid');
});
}
} });
Related
I have a Thymeleaf form.
One of the input fields is like this:
<input type ="text" id="customer" class="floatLabel" name="customer" th:field = "*{customer.idCustomer}">
<label for="customer">Customer</label>
I want to use jQuery UI. In my Java app, it works and the app sends JSON with correct values. But my auto suggestion list is empty.
I included one css library in my html head section and few script libraries at the bottom of body part.
Libraries are:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
jQuery code:
<script>
$("#customer").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/search_customer",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#customer').val(ui.item.value); // save selected id to input
$('#customer').val(ui.item.label); // display the selected text
return false;
}
});
Java controller:
#PostMapping("/search_customer")
#ResponseBody
public List<Object[]> searchTerm(#RequestParam(name = "search", required = false) String searchTerm)
{
List<Object[]> customers = customerDAO.getCustomers(searchTerm);
return customers;
}
JpaRepository:
#Repository
public interface ICustomerRepository extends JpaRepository<CustomerDTO, Integer>
{
#Query(value = "SELECT c.idCustomer, c.ingameName FROM CustomerDTO c WHERE c.ingameName LIKE :term%")
public List<Object[]> findCustomersAutocomplete(String term);
}
So, everything works fine, I get JSON array and each element has one integer and one string. In that thymeleaf input field I want labels to be string "ingameName" and value (user shouldn't see that) is idCustomer.
JSON that I received looks like this:
[[1, "customer1"], [3, "Customer2"]]
0: [1, "customer1"]
0: 1
1: "customer1"
1: [3, "Customer2"]
0: 3
1: "Customer2"
So I want labels to be customer1 and Customer2 and values that should be saved are 1 or 3.
But I don't know how to tell jQuery UI what is label and what is id?
I followed this tutorial:
https://makitweb.com/jquery-ui-autocomplete-with-php-and-ajax/
As your data recieve from backend(controller) is not in format which autocomplete plugin accept so you can create that format inside success function of ajax . You just need to loop through your data using each loop and then push array value in key-value pair in JSON Array and then pass same to your plugin.
Demo Code :
var data = [
[1, "Customer1"],
[3, "Customer2"]
];
$("#customer").autocomplete({
source: function(request, response) {
/*$.ajax({
//some codes
success: function( data ) {*/
var json_array = [];
//create format like autocompltee
$(data).each(function(i, val) {
//create obj and push value in main_array
json_array.push({
"label": val[1],
"value": val[0]
})
})
console.log(json_array)
response(json_array);
/* }
});*/
},
select: function(event, ui) {
$('#customer').val(ui.item.label);
$('#ids').val(ui.item.value);
return false;
}
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="customer" class="floatLabel" name="customer">
<input type="text" id="ids">
<label for="customer">Customer</label>
/* How do I Display json data into a table in a JSP Page with a submit button in each row. On clicking submit button, Row data should be sent to a servlet.
I have fetched json data from a Servlet using Ajax.
Below is my ajax call to get JSON data from Servlet */
function updateprofile(){
$.ajax({
url : 'abc/ConnectionInfo',
type: 'GET',
data: {},
data type: 'json'
}).done(function (data){
renderProfiles(data);
}).fail(function (){
toaster.error("Eror...");
});
}
function
renderProfiles(data){
//How can I implement this
method to display all the
data in table format with a
button corresponding to
each row. And on clicking
of the button it should
send a profile ID to
Servlet Post method.
}
You can use $.foreach loop to iterate your json data and show them in your table. Demo code(you need to do changes in below code as per your requirment) :
//your json data
var response = [{
"metric": "connected[qa_KCDz->Exre]"
},
{
"metric": "connected[qa_KTDz->Exre]"
},
{
"metric": "connected[qa_KPDz->Exre]"
}
];
var str = '<table border=1><tr>\n' +
'<th>Something</th>\n' +
'<th>Submit</th>\n' +
'</tr>';
//looping through json data
$.each(response, function(key, value) {
//get value
var s = value['metric'];
//getting index of [
var i = s.indexOf('[');
var data = s.slice(10, i + 8).trim();
str += '<td>' + value['metric'] + '</td>';
str += '<td> <form method="post" action="servletname"><input type="hidden" name="data" value=' + data + ' ><input type="submit" value ="send" ></form></td></tr>';
});
str += "</table>";
//appending data
$("#table").html(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"> </div>
Put above code of jquery under your function renderProfiles(data){..}.Also,under <form></form> tag i have added a hidden input field with the required value that you need to send to your servlet .Get that value using request.getParameter("data") in doPost method of servlet.
I'm using the next Spring form tag on my project:
<form:select path="eps.eps_id_eps" id="entidad" style="width: 400px;">
<form:options items="${EPSs}" />
</form:select>
I need to change the "items" values so i can display another data to a same select form tag, i.e. dynamically 'items="${EPSs}"' changes to 'items="${foo}"'
IS THERE Any mode to change items value in js/jquery or by ModelAttribute tag in server side?
Step 1 : Define a controller to receive foo list
#RestController
public class FooController{
#GetMapping("/foo")
public List<String> getFooItems(#RequestParam String eps){
return Arrays.asList("foo1","foo2");
}
}
Step 2 : Define a jquery to listen on eps select changes
$(document).ready(function(){
$("#entidad").change(function(){
var eps = $(this).val();
$.ajax({
url: '/foo?eps='+eps,
type: 'GET',
success:function(response){
var len = response.length;
//clear previous selection, eps_select is the select you want to complete
$("#eps_select").empty();
for( var i = 0; i<len; i++){
var foo = response[i];
$("#eps_select").append("<option value='"+foo+"'>"+foo+"</option>");
}
}
});
});
});
I have a jsp page which has java scriplets, and which is displaying the required output using out.println(obj), but I want to return this 'obj' so that these values can be used in another js file. How to return this from the jsp page?
So the js file is:
(function() {
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
var gridOptions = {
columnDefs: [
{headerName: 'CLIENT_ACRONYM', field: 'CLIENT_ACRONYM'},
{headerName: 'ORDER_QTY', field: 'ORDER_QTY'},
]
};
new agGrid.Grid(gridDiv, gridOptions);
jsonLoad( function(data) {
gridOptions.api.setRowData(data);
});
});
})();
function jsonLoad(callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '../output.json'); // by default async
xhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {
if(this.status == 200) {// onload called even on 404 etc so check the status
callback(this.response);
}
};
xhr.onerror = function() {
console.log('loading data error');
};
xhr.send();
}
JSP file returning Jsonarray:
JSONArray jsonArray = new JSONArray(orderDetailsList1);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArray);
So, instead of output.json in the js file I need to pass the JSOn Object returned by the jsp file. How to do that?
Use this code in jsp file
<input type="hidden" value="<%out.println(obj);%>" id="objValue"/>
In js file you can get the value by its id as
var objValue = document.getElementById("objValue");
Basically scriplets in jsp is not good.
Store in session scope or request scope and use it,like session.setAttribute('obj','value') in servlet and value="${obj}" in jsp.
Put that value in <div id=""> or <p id=""> tag which has ID in jsp and get that value in any js using getElementByID.
I have done this ajax code to send data from jsp to servlet.
My ajax code in jsp is as follows:
$(document).ready(function(){
$("#process").click(function(){
console.log($("#processlist").val());
$.ajax({
url: "processtimesheet.do",
type : 'POST',
data : {processlist : $("#processlist").val()},
success : function(response){
alert(response);
window.location.reload(true);
}
})
});
});
The value in JSP is getting picked from the below EL.
<input type="hidden" name="processlist" id="processlist" value="${timesheetList}">
I am getting the values in the servlet..
[com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16]
How do I convert these values back into List ?
If you right click and inspect near that hidden input element, you can see that input, in fact, has the value like com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16 . The data is unusable.
This means you embedded full object to the input field. You can instead use/embed any unique field of Timesheet type and return that list to servlet. Then you can identify which list is selected at server side.
Assuming you have id field in Timesheet class, construct an id list:
<input type="hidden" name="processlist" id="processlist" value="${timesheetIdList}">
And servlet:
Map<Integer, Timesheet> index = ...;// map (unique index) construction
List<Timesheet> listSelected = new ArrayList<>;
for(int i = 0; i<idarray.length; i++) {
if(index.containsKey(idarray[i])) {
listSelected.add(index.get(idarray[i]))
}
}