post ajax data to spring controller - ajax

I am a newbie to AJAX and i am trying to configure a simple method to post data into the controller using ajax only since i'm not sufficient in JSON
,lambda expressions other than Java can someone tell me what is the mistake i'm doing that this ajax method is not working?
Controller
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String addCart(int val1, int val2) {
System.out.println("+++++++++++++++++++++++++++++" + val1);
System.out.println("+++++++++++++++++++++++++++++" + val2);
return "redirect:/viewResult";
}
Ajax/Script
$(document).on('change', '._someDropDown', function (e) {
var x = this.options[e.target.selectedIndex].text;
var y = $(this).data('idtest');
alert(x);
alert(y);
$.ajax(
{
url: "/HRS/test",
data: {val1: x, val2: y},
method: 'POST'
});
});
note that these alerts(x and y values) are shown correctly.I just want to send them to my controller.Please any suggestions?

First of all you need to make your Controller accept a POST Request which your AJAX code would be sending.
Then you need to add a RequestBody Annotation over the POJO that you wish to accept from AJAX.
Let's say you need to send var x, y. Create a class like this:
public class MyData {
String x;
String y;
// getters/setters/constructor
}
Then you need to create MyData in your AJAX Call & pass it.
$(document).on('change', '._someDropDown', function (e) {
var myData = {
"x" : this.options[e.target.selectedIndex].text,
"y" :$(this).data('idtest')
}
.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/HRS/test", //assuming your controller is configured to accept requests on this URL
data: JSON.stringify(myData), // This converts the payLoad to Json to pass along to Controller
success :function(result) {
// do what ever you want with data
}
});
Finally your controller would be something llike:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public #ResponseBody String addCart(#RequestBody MyData data) {
System.out.println(data.getX());
System.out.println(data.getY());
return something;
}
My knowledge is a bit rusty but I hope you get the idea how this works!

Related

Pass a form and an array through a single ajax

I'm trying to pass a serialized form and an array through a single ajax call. I'm getting an error everytime I submit. I want to receive both in my controller and I have no idea how to do it. This is my code based on other tutorials I found online but it doesn't work.
ajax call:
var o = Array.prototype.slice.call(document.getElementsByName("client_beneficiary[]")).map(e => e.value);
$.ajax({
url: "/SaveProductApplication",
type: "post",
data: {
$("#product_form").serialize(),
beneficiary_list: o
},
success: function() {}
});
controller:
#RequestMapping(value= "/SaveProductApplication", method=RequestMethod.POST)
public #ResponseBody boolean save(ProductApplication productApplication, #RequestParam(value="beneficiary_list[]") String[] beneficiary_list) {
for (String arrElement : beneficiary_list) {
System.out.println("Item: " + arrElement);
}
}
hoping you could help me. thank you!

Sending data to MVC Controller with AJAX

I am trying to send data with AJAX to MVC Controller method, but I don't know what am I doing wrong.
Here is the AJAX call
$.ajax({
type: 'POST',
url: invokingControllerActionUrl,
data: "it is just a simple string",
success: function (data) {
window.location.href = link;
}
});
And here is the controller method. It is invoked, but the parameter is always null.
public IActionResult OnPostTest([FromBody] string stringValue)
{
// stringValue is always null :(
}
Change you ajax call to this
$.ajax({
type: 'POST',
url: invokingControllerActionUrl, // Confirm the Path in this variable Otherwise use #Url.Action("OnPostTest", "InvokingController")
data: {stringValue: "it is just a simple string"},
success: function (data) {
window.location.href = link;
}
});
And remove the [FromBody]. ALso its better to define type post. Not necessary though
[HttpPost]
public IActionResult OnPostTest( string stringValue)
{
// stringValue is always null :(
}
Depending on what Content-Type you are sending from JS, you might need to encode your string properly, as a form-value
...
data: 'stringValue="it is just a simple string"',
...
or e.g. JSON:
...
data: '{stringValue: "it is just a simple string"}',
...
See also this discussion
I haven't found an easy way to pass a string of unformatted data via parameter, unfortunately. According to this answer, you can do the following:
public IActionResult OnPostTest()
{
Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string stringValue = new StreamReader(req).ReadToEnd();
...
// process your stringValue here
...
}

how to send an object from spring controller to jsp through Ajax

I have a transaction object and I am trying to send the object to the front page. I have no problem when I try to send a string, but I couldn't send an object.
So this is my controller:
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET)
#ResponseBody
public MyTransaction helloahjax() {
System.out.println("hello Ajax");
MyTransaction tran = MyTransaction.getInstance();
tran.setId(123);
return tran;
}
#RequestMapping(value="/result", method=RequestMethod.GET)
public String show() {
return "result";
}
and this is my ajax call
button
<div class="result"></div>
function doajax() {
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
$('.result').html(response.id);
},
error: function() {
alert("asda");
}
});
};
I search around and see that other developers used "response.result.id" but I couldn't make it neither. Any suggestion please.
I would suggest to change your code like below.
1.Include JSON library to your classpath and add produces="application/json" attribute to RequestMapping for the helloahjax method.
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET,produces="application/json")
2.Include dataType in your ajax call,like below
$.ajax({
type : 'GET',
dataType : 'json',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
var obj = JSON.parse(response);
//Now you can set data as you want
$('.result').html(obj.id);
},
error: function() {
alert("asda");
}
});
The URL would change to below when you are returning JSON from the controller method. In this case you don't need to parse the response. Instead you can directly access the object variables as response.abc
${pageContext.request.contextPath}/result/helloajax.json

How to pass Json object from ajax to spring mvc controller?

I am working on SpringMVC, I am passing data from ajax to controller but i got null value in my controller please check my code below
function searchText()
{
var sendData = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
url: "/gDirecotry/ajax/searchUserProfiles.htm,
async: true,
data:sendData,
success :function(result)
{
}
}
MyControllerCode
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(HttpServletRequest request)
{
String pName = request.getParameter("pName");
//here I got null value
}
any one help me
Hey enjoy the following code.
Javascript AJAX call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.html",
data: JSON.stringify(search), // Note it is important
success :function(result) {
// do what ever you want with data
}
});
}
Spring controller code
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search search, HttpServletRequest request) {
String pName = search.getPName();
String lName = search.getLName();
// your logic next
}
Following Search class will be as follows
class Search {
private String pName;
private String lName;
// getter and setters for above variables
}
Advantage of this class is that, in future you can add more variables to this class if needed.
Eg. if you want to implement sort functionality.
Use this method if you dont want to make a class you can directly send JSON without Stringifying. Use Default Content Type.
Just Use #RequestParam instead of #RequestBody.
#RequestParam Name must be same as in json.
Ajax Call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
/*contentType : 'application/json; charset=utf-8',*/ //use Default contentType
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.htm",
data: search, // Note it is important without stringifying
success :function(result) {
// do what ever you want with data
}
});
Spring Controller
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestParam String pName, #RequestParam String lName) {
String pNameParameter = pName;
String lNameParameter = lName;
// your logic next
}
I hope, You need to include the dataType option,
dataType: "JSON"
And you could get the form data in controller as below,
public #ResponseBody String getSearchUserProfiles(#RequestParam("pName") String pName ,HttpServletRequest request)
{
//here I got null value
}
If you can manage to pass your whole json in one query string parameter then you can use rest template on the server side to generate Object from json, but still its not the optimal approach
u take like this
var name=$("name").val();
var email=$("email").val();
var obj = 'name='+name+'&email'+email;
$.ajax({
url:"simple.form",
type:"GET",
data:obj,
contentType:"application/json",
success:function(response){
alert(response);
},
error:function(error){
alert(error);
}
});
spring Controller
#RequestMapping(value = "simple", method = RequestMethod.GET)
public #ResponseBody String emailcheck(#RequestParam("name") String name, #RequestParam("email") String email, HttpSession session) {
String meaaseg = "success";
return meaaseg;
}

Parameter to Web Service via Jquery Ajax Call

I am using revealing module pattern and knockout to bind a form. When data is entered in that form(registration), it needs to be posted back to MVC4 web method.
Here is the Jquery code
/*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {
// Private Area
var _tmpl = { load: "Loading", form: "RegisterForm"};
var
title = ko.observable(null)
template = ko.observable(_tmpl.load),
msg = ko.observable(),
postData = ko.observable(),
PostRegistration = function () {
console.log("Ajax Call Start");
var test = GetPostData();
$.ajax({
type: "POST",
url: obj.postURL, //Your URL here api/registration
data: GetPostData(),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8'
}).done(Success).fail(Failure);
console.log("Ajax Call End");
},
GetPostData = function () {
var postData = JSON.stringify({
dummyText1: dummyText1(),
dummyText2: dummyText2(),
});
return postData;
}
return {
// Public Area
title: title,
template: template,
dummyText1: dummyText1,
dummyText2: dummyText2
};
}();
The controller code is simple as per now
// POST api/registration
public void Post(string data)
{
///TODO
}
When i am trying to, capture the data (using simple console.log) and validate it in jslint.com, it's a valid Json.
I tried hardcoding the data as
data: "{data: '{\'name\':\'niall\'}'}",
But still i get as null, in my web method.
Added the tag [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] to my Post method in controlled, but still no fruitful result
Even tried JSON.Stringify data: JSON.stringify(data) but still i get null in my web-method.
I am not able to figure out the solution.
Similar issue was found # this link
http://forums.asp.net/t/1555940.aspx/1
even Passing parameter to WebMethod with jQuery Ajax
but didn't help me :(
MVC and WebApi uses the concept of Model Binding.
So the easiest solution is that you need to create a Model class which matches the structure of the sent Json data to accept the data on the server:
public void Post(MyModel model)
{
///TODO
}
public class MyModel
{
public string DummyText1 { get; set; }
public string DummyText1 { get; set; }
}
Note: The json and C# property names should match.
Only escaped double-quote characters are allowed, not single-quotes, so you just have to replace single quotes with double quotes:
data: "{data: '{\"name\":\"niall\"}'}"
Or if you want to use the stringify function you can use it this way:
data: "{data: '" + JSON.stringify(data) + "'}"

Resources