Send javascript variables to spring controller - javascript

I'm trying to develop simple application using spring mvc and I need to pass javascript parameters to spring controller. I have tried several methods and none of them were worked. Following is my javascript and spring controller. Please help me to sort this issue.
Java script
function searchViaAjax(id) {
alert(id);
$.ajax({
type : "POST",
contentType : "application/json",
url : "search/api/getSearchResult",
data : JSON.stringify(id),
dataType : 'json',
timeout : 100000,
success : function(id) {
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
AjaxController.java
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult")
public String getSearchResultViaAjax(#RequestParam(value = "id") int id) {
System.out.println("come to ajax"+ id);
return "hello";
}
}

When you pass json as requestbody then above call is applicable. To send request param you have to as below:
Use following ajax call:
function searchViaAjax(id) {
var tempId = id;
$.ajax({
type : "POST",
url : "/search/api/getSearchResult",
data : {id:tempId},
timeout : 100000,
success : function(id) {
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
also you can acheive this using get method as below:
function searchViaAjax(id) {
$.ajax({
type : "GET",
url : "/search/api/getSearchResult/"+id,
timeout : 100000,
success : function(id) {
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult/{id}")
public String getSearchResultViaAjax(#PathVariable(value = "id") Integer id)
{
return String.valueOf(id);
}
}

When you use JSON.stringify, you are actually sending a JSON object to your spring controller's method. All you have to do is wrap your json object as a java object like so.
public class UserId {
private int id;
// setters and getters
}
And in your controller's method use #RequestBody to map your JSON to your UserId class like so
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult", method = RequestMethod.POST)
public String getSearchResultViaAjax(#RequestBody UserId user) {
System.out.println("come to ajax" + user.getId());
return "hello";
}
PS: Haven't tested it but should work.

It is a post request you are making from your ajax to controller.
You are missing "methodType=RequestMethod.POST" on your spring controller.
Replace #RequestMapping(value = "/search/api/getSearchResult") with
#RequestMapping(value = "/search/api/getSearchResult", methodType=RequestMethod.POST)

Related

Problem with jQuery post to ASP.NET Core controller

I have gone through this solution on stackoverflow but I couldn't solve my problem.
In HomeController I have a method named as Audit which I want to be posted from /Home/Index page's script through jQuery. The controller looks like:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody] JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}
In the /Home/Index pages's javascript file I have tried to post a JSON Object to that Audit in a way like this:
var auditData = {};
$(document).ready(function(){
var request = $.getJSON('http://www.geoplugin.net/json.gp', function (responseData, status) {
auditData = {
Latitude : responseData.geoplugin_latitude,
Longitude : responseData.geoplugin_longitude
};
$.post('Audit', auditData, function (response) {
console.log(response);
});
});
});
I want the auditData object to be posted as JObject in /Home/Audit but something is going wrong. I think there is problem either in controller or, in $.post method. How can I solve this problem?
Your post URL is wrong, and you need to name the data you're posting back as jObject as well to match what you defined in your controller.
$.post('#Url.Action("audit", "home", new { area = "" })', { jObject: auditData },
function (response) {
console.log(response);
});
There are multiple issues in your current code, check points below one by one:
As the suggestion from Rory, your request url is wrong, which should be Home/Audit
If you post request without antitoken, you should remove [ValidateAntiForgeryToken]
You should post request data with json instead of form data.
Code:
Client
#section Scripts{
<script type="text/javascript">
var auditData = {};
$(document).ready(function(){
auditData = {
Latitude : "l1",
Longitude : "l2"
};
$.ajax({
type: 'POST',
url: 'Home/Audit',
data: JSON.stringify(auditData),
success: function(data) { alert('data: ' + data); },
contentType: "application/json"
});
});
</script>
}
Server:
public class HomeController : Controller
{
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody]JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}

Send ararylist from js to spring controller

I want to send an arrayList from javaScript to spring controller, I have written this code but it doesn't work, when I call this function nothing happens.
function order_(){
var itemOrder = $('#sortable').sortable("toArray");
$.ajax({
contentType:"application/json;",
type : "POST",
url : "/my_url",
data : (itemOrder),
dataType: "json",
success: function (data) { alert("Mapping Successful") },
failure: function (data) { alert("not working..."); }
});
}
My spring controller
#RequestMapping(value = "/my_url", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String getItemOrder(#RequestBody String[] itemOrder) {
// code to get itemOrder }
Is there something wrong in this code?

How to pass a java variable to a different jsp page containing javascript?

my java class:
#RequestMapping(value = "/front", method = RequestMethod.GET)
public String onemethod(#RequestParam String name, Model model) { String str = "something";
model.addAttribute("str", str);
return "jsppage";
}
jsp page:
var arrayCollection = ${str}
With this code, I'm getting 404 exception on Tomcat. I'm unable to send java variable to a different jsp page. Any help would be appreciated for this case.
Ok to wrap this up:
2 choices:
add variable to the model and access it directly in JSP
make it a rest method and call from ajax
Examples:
Ad.1.:
Controller
import org.springframework.ui.Model;
#RequestMapping(value = "/front", method = RequestMethod.GET)
public String onemethod(Model model) throws IOException, ParseException {
String str = "something";
model.addAttribute("str", str);
return "jsppage";
}
JSP ("jsppage")
var test = '${str}';
Ad.2.:
Controller
// just to show JSP
#RequestMapping(value = "/front", method = RequestMethod.GET)
public String onemethod() throws IOException, ParseException {
return "jsppage";
}
// REST
#ResponseBody
#RequestMapping(value = "/rest", method = RequestMethod.GET)
public String secondmethod() {
return "something";
}
JSP ("jsppage")
$.ajax({
method : "get",
url : "rest",
dataType : 'text',
success : function(data) {
console.log(data);
},
error : function(e){
console.log(e);
}
});
If you want to also send "name" parameter, add #RequestParam String name to the controller method and call ajax like this:
$.ajax({
method : "get",
url : "rest",
dataType : 'text',
data : {"name" : "some name"},
success : function(data) {
console.log(data);
},
error : function(e){
console.log(e);
}
});

How to pass a list from spring controller to ajax in jquery

This is my Jquery! Here i am not getting success response, instead a error response is thrown when a list is returned from controller to below jquery. Please let me know where i am going wrong.
//ajax method to retrieve the data from controller where controller returns list
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1.html",
data: "pid=" + pid,
success: function (response) {
alert(response.list4);
$.each(response, function (index, datec) {
alert(datec.name); //to print name of employee
});
},
// Even though controller returns the list,but i am not getting the above success response,instead below error method is executed.
error: function (e) {
alert('Error: ' + e);
}
});
}
Below is the controller which returns the list.
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#ModelAttribute("s") Iochart s) {
System.out.println("Patient"+s.getPid());
List<Iochart> list4 = dao.getPatientdet1(s.getPid());
return list4;
}
getPatientdet1() which retrieves the data from database
public List<Iochart> getPatientdet1(String pid) {
// TODO Auto-generated method stub
System.out.println(pid);
return template.query(
"select pid,name,fileno,age,gender,date,wardno,doctord,doctsig,ratef,nursesig,time,type,amount,typecommence,amtgiv,urine,vomitus,remarks from iochart where pid='"+pid+"'",
new RowMapper<Iochart>() {
public Iochart mapRow(ResultSet rs, int row) throws SQLException {
Iochart i = new Iochart();
i.setPid(rs.getString(1));
i.setName(rs.getString(2));
i.setFileno(rs.getString(3));
i.setAge(rs.getString(4));
i.setGender(rs.getString(5));
i.setAdmdate(rs.getString(6));
i.setWardno(rs.getString(7));
i.setDoctord(rs.getString(8));
i.setDoctsig(rs.getString(9));
i.setRatef(rs.getString(10));
i.setNursesig(rs.getString(11));
i.setTime(rs.getString(12));
i.setOraltype(rs.getString(13));
i.setOralamt(rs.getString(14));
i.setOralcommence(rs.getString(15));
i.setAmtgiv(rs.getString(16));
i.setUrine(rs.getString(17));
i.setVomitus(rs.getString(18));
i.setRemarks(rs.getString(19));
System.out.println(rs.getString(2));
return i;
}
}
);
}
Change your controller method like so. Mind the #RequestParam that is used to get the pid
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#RequestParam(name = "pid") String pid) {
return dao.getPatientdet1(pid);
}
And your ajax url like so
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1", //Don't postfix .hmtl
data: "pid=" + pid,
...
});
}

Getting failed on returning string from API to JSON AJAX POST in mvc Javascript

$("#modelchange").change(function() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetStore")',
dataType: 'json',
data: {
Id: $("#modelchange").val()
},
success: function(storeName) {
$('#storeName').text("Store : " + storeName);
},
error: function(ex) {
alert('Failed to load store Value');
}
});
return false;
});
API
[HttpPost]
public string GetStore(int Id)
{
string storeName = db.AddInktoStores.Single(a => a.InkId == Id)).Store.StoreName;
return storeName;
}
Above mentioned is a controller and JSON in my javascript.
I am trying to get Store Name but I keep getting throw into my error: function
Please Help!
Try to return data as:
[HttpPost]
public JsonResult GetStore(int Id)
{
string storeName = db.AddInktoStores.Single(a => a.InkId == Id)).Store.StoreName;
return Json(storeName);
}

Categories

Resources