Kendo UI grid custom datasource URL - java

I have a comboBox called clientCCBox, I need a javascript that retrieves the selected option value, wich will be the client id, and then passes it on the kendo grid datasource read property as follow:
<kendo:dataSource-transport-read url="/read.html?*clientID*"/>
I've been trying to use this js snippet to recover the selected value; the document write is there to visually see if it actually retrieved the value, but it displays nothing. How would I once I get the clientID use it in HTML?
<script>
function onSelect(e){
var clientId = clientCCBox.value();
document.write(clienteId);
}
</script>
If I do manage to pass clientID on the querystring, the following code on the controller would return a list and populate the grid right?
#RequestMapping(value = "/read.html*")
public #ResponseBody List<Workers> read(HttpServletRequest request) {
return workerDAO.listWorker(Integer.parseInt(request.getQueryString()));
}

You can define your additional parameters using parameterMap attribute in kendo:dataSource-transport tag.
Example:
<kendo:dataSource-transport parameterMap="additionalParameters">
<kendo:dataSource-transport-read url="/ListBeer" type="GET" contentType="application/json"/>
</kendo:dataSource-transport>
Where additionalParameters is:
<script type="text/javascript">
var theId = "xyz";
function additionalParameters(data, type) {
if (type === "read") {
return "id=" + theId;
}
return data;
}
</script>
Here, I would be loading data from the following url /ListBeer?id=xyz where xyz is the value of theId.
You can also send more than one parameter:
function additionalParameters(data, type) {
if (type === "read") {
return "id=" + data + "&param=" + JSON.stringify(data);
}
return "param= "+ JSON.stringify(data);
}

Use the "Data" event on the read action parameter for the drop down to specify dynamic javascript parameters to the drop down. Note the exact syntax for the .Read method. Often you see the syntax .Read("ActionName", "ControllerName") but we want the other overloaded version of .Read:
.DataSource(data => data.Read(read => read.Action("GetDropDownValues", "Quote").Data("getCriteria")))
function getCriteria() {
return {
id: "put value here",
anotherParameter: 55
};
}

you need to put the client id in the data field of the transport.
Look at the following link.
http://docs.kendoui.com/api/framework/datasource#transportcreatedata-objectstringfunction
this is part of jquery not kendo ui

Related

struts2 ajax call response always shows null

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null
All setters and getters are set correctly and they are working fine when I see in debug sysouts
Action Class
#Override
#Action(value = "/search",
results = { #Result(name = "success", type="json")})
public String execute() throws ParseException
{
this.setName(this.term+": "+this.pos);
System.out.println("Name: "+Name);
JSONObject json = (JSONObject)new JSONParser().parse(Name);
return ActionSupport.SUCCESS;
}
jsp
function Search()
{
var term = document.getElementById("term").value;
var pos = document.getElementById("pos").value;
var itr = document.getElementById("itr").value;
var pri = document.getElementById("pri").value;
var atb = document.getElementById("atb").value;
var jsonData = {};
jsonData.term = term;
jsonData.pos = pos;
jsonData.itr = itr;
jsonData.pri = pri;
jsonData.atb = atb;
$.ajax({
type: "POST",
url: "search",
dataType: "json",
data: jsonData,
success: function(response){
console.log(""+response);
alert('Name: '+response.Name);
//alert('Length: '+data[0].length);
/* $.each(data[0],function(index, value){
alert("value " +value);
});*/
},
error: function(response){
alert(response);
alert(response.length);
$.each(response,function(index, value){
alert("value " + value);
});
}
});
}
I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?
As clearly explained in this answer, you need to use the JSON plugin, that will serialize the entire action (or a single root object when needed). You don't need then to do the parsing yourself, just evaluate the name variable.
To send JSON from JSP to action instead you need to use the JSON Interceptor in your stack.
Ensure you have getters and setters for everything.
Your Name variable should be name, both in Java and in Javascript. Only the accessors / mutators should use the capitalized N (getName, setName).
If the error persists, check carefully console and logfiles for errors, with devMode set to true.
Since this comment has gone too far, I've turned it into an answer :)

How to make ajax get call for text to Java controller in Spring MVC?

I am expecting a BigDecimal.toString() value from Web call.
But i am not manage to configure it and getting either 404-Not found or 406.
Following is Spring MVC Code
#RequestMapping(value="get/myData", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String getMyData(#ModelAttribute("user") User user,
#ModelAttribute("detailForm") DetailForm form)
{
//A web service called return big decimal and return that big decimal value toString
return "Value";
}
Following is calling code:
var convId = $("#" + $("body form:first").attr("id")).find('input[name="_CONV_ID"]').val();
blockUI: false,
dataType: 'text',
type: 'GET',
url: "get/myData.do",
data: { '_CONV_ID': convId},
success: function (data) {
// new dialog
alert(data);
},
error: function (result) {
alert("Error" + result);
}
Could anyone please help me in adjusting code. On button click, a value is getting return from web service which is of BigDecimal type
Trying reaching the url http://localhost:8080/your_application_name/get/myData. If you find 404 error there, you need to check your web.xml. Check the section of servlet-mapping part.

calling a Java method by AJAX

Actually I've been reading about this for a while but I couldn't understand it very well.
Here is a snippet of the Servlet "ProcessNurseApp" :
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true) {
// Show him an alert and stop him from applying.
out.println("<script>\n"
+ " alert('You already Applied');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
So when the form named "ApplicationForm" in the "Nurses.jsp" get submitted it goes to that method in servlet after some Javascript validation.
My issue is that I want to call that method
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true)
in the JSP page without getting to servlet so I can update values without refreshing the page. I've been reading that using ajax with jQuery would be the best way to do that, so can anyone help me of calling the above if statement from jQuery by AJAX.
Try an ajax call to the servlet(not possible without calling servlet) to check whether the function returns true or false then return a flag according to the value(true or false). On that basis you can show an alert or anything else.
For ajax call, you can use:
$.post( "ajax/Servlet_Url", function( data ) { if(data==true) alert("You already Applied"); else window.history.go(-1);});
Refer to following Link for more details about jQuery post request.
https://api.jquery.com/jquery.post/
jQuery(document).ready(function($) {
$("#searchUserId").attr("placeholder", "Max 15 Chars");
$("#searchUserName").attr("placeholder", "Max 100 Chars");
$.ajax({
url:"../../jsp/user/userMaster.do",
data: { drpType : 'userType',lookType : "1" },
success: function (responseJson) {
var myvalue = document.getElementById("userTypeKey");
for(var val in responseJson)
{
valueType = val;
textOptions = responseJson[val];
var option = document.createElement("option");
option.setAttribute("value",valueType);
option.text = textOptions;
myvalue.add(option);
if(valueType == myvalue.value)
{
option.selected = "selected";
}
}
}
});
});

Want to pass the java value into javascript function in jsp

I am trying to pass a string value to a JavaScript function by taking from request parameter in JSP, in my struts based project. here is the code:
<%
String timeVal = "Not found";
if(request.getAttribute("myDate")!=null){
timeVal= (String)request.getAttribute("myDate");
}
%>
and then pass it in function as parameter
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('update', <%=timeVal %>)">Save</html:submit>
Where the JavaScript function is
function SubmitPage(action, aa)
{
alert("Date is ...." + aa);
}
But when i try to run this it gives me an error
HTTP Status 400 - Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
With message on web page.
Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
Thanks in advance.
EDIT Here is stack trace
[ERROR] DispatchAction - -Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
it's work for me :
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('<%=timeVal %>')">Save</html:submit>
('<%=timeVal %>') // between single Quotation
Rather using that i will advise you to use value like this in your JavaScript function
var tt = <%=(String)request.getAttribute("myDate")%>
alert(tt+ "Done this....");
Hope this will help you.
Use '<%=timeVal %>' instead of <%=timeVal %> in Javascript method:
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('update', '<%=timeVal %>')">Save</html:submit>

How do I access POST variables in my controller?

I am making the following AJAX request:
$.post('/route', {
arg1 : 'foo',
arg2 : 'bar'
});
Through the route:
POST /route controllers.Test.readPost()
How do I access these POST variables in the method of my controller?
public static Result readPost() {
return TODO; // read post variables
}
I cannot find a simple way of doing this in the documentation. It only states how to get values from JSON requests.
Use DynamicForm
public static Result getValues(){
DynamicForm requestData = form().bindFromRequest();
String name = requestData.get("name");
String desg = requestData.get("desg");
// etc
return ok("You sent: " + name + ", " + desg);
}
There is also other possibility to construct AJAX query and pass arguments via javascriptRoutes: https://stackoverflow.com/a/11133586/1066240
Of course it will pass the params via URL so it's not suitable for every value, but in many places it will be goot enough for sending POST requests with AJAX. Of course javascriptRoutes create the request with type set in routes file.
BTW: it was better if you wrote which version you are using.
you can use GET with an ajaxRequest. more information can be found here http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml
var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mygetrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)

Categories

Resources