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

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;
}

Related

How to send Long and Double through Ajax to Spring controller?

I want to send Long and Double to Spring controller use Ajax.
var id = $(this).data('customer-id');
var quantity = $('#quantity-' + id).val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
url: '/changeQuantityOrder',
data: {idOrder: id, quantityChange: quantity},
error: function(e) {
console.log(e);
},
success: function (msg) {
window.location.href = "/administrationNotSleeps";
}
I try to receive a code so:
#RequestMapping(value = "/changeQuantityOrder", method = {RequestMethod.POST})
public #ResponseBody Long editCustomerOrder(#RequestParam(value = "idOrder")Long id,
#RequestParam(value = "quantityChange")Double quantity){
System.out.println("Id:"+id+" Quantity "+quantity );
return id;
}
But I receive exception
{"timestamp":1490775639761,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Long parameter 'idOrder' is not present","path":"/changeQuantityOrder"}"
I looked for and have found about this exception (MissingServletRequestParameterException) https://stackoverflow.com/
But this article was written 3 years ago, maybe something changed?
Because now I send String to Spring controller and after that I use split in java.
key should be in quotes
data: {"idOrder": id, "quantityChange": quantity}
Also mention dataType - what kind of response to expect.

post ajax data to spring controller

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!

MVC Controller post json does not work

I have the this code to post json to a controller.
The problem is that the credentials object does not get populated with the posted values.
How do I change this code so that it works?
I see in Fiddler that the request is being posted correctly.
[HttpPost]
public JsonResult Authenticate(CredentialsModel credentials)
{
return Json(credentials);
}
[DataContract]
public class CredentialsModel
{
[DataMember(Name = "user")]
public string User;
[DataMember(Name = "pass")]
public string Pass;
}
$.ajax({
type: "POST",
url: "/login/authenticate",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"user":' + JSON.stringify($('#username').val()) + ',"uass":' + JSON.stringify($('#userpass').val()) + '}',
dataType: "json",
timeout: 100,
success: function (msg) {
},
complete: function (jqXHR, status) {
if (status == 'success' || status == 'notmodified') {
var obj = jQuery.parseJSON(jqXHR.responseText);
}
},
error: function (req, status, error) {
}
});
The default MVC model binder only works with properties. Your CredentialsModel is using fields. Try changing them to properties. You can also remove the annotations.
public class CredentialsModel
{
public string User { get; set; }
public string Pass { get; set; }
}
Also, as pointed out by Sahib, you can create a Javascript Object and then stringify it, rather than stringifying each one. Although that doesn't appear to be the problem in this case.
data: JSON.stringify({
User: $('#username').val(),
Pass: $('#userpass').val()
})
Try chaning your data like this :
$.ajax({
.................
//notice the 'U' and 'P'. I have changed those to exactly match with your model field.
data: JSON.stringify({User: $('#username').val(),Pass: $('#userpass').val()}),
.................
});

Null parameter when use Ajax post

I have found several answers (here for example) but they do not seem to solve my problem.
var result = {
command: 'exportWAV',
type: type
};
$.ajax({
url: 'SubmitSound',
type: 'Post',
data: JSON.stringify(result),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
alert(msg);
}
});
Back end code
[HttpPost]
public ActionResult SubmitSound(string blob)
{
// Create the new, empty data file.
string fileName = AppDomain.CurrentDomain.BaseDirectory + "/Content/Sound/" + Environment.TickCount + ".wav";
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(blob);
w.Close();
fs.Close();
return new JsonResult() { Data = "Saved successfully" };
}
result is not null because this.postMessage = result; send a file back to client side for downloading. w.Write(blob) keeps complaining that blob cannot be null.
How can I make it work? Thank you and best regards
Do this:
data: JSON.stringify({ blob: result}),
You may want to change your string param in your controller action, for an object with the same structure of your JSON... that means the same attributes names.
The object should be something like this:
public class MyBlob{
public string command {get; set;}
public string type {get; set;}
}
So, your action should be:
public ActionResult SubmitSound(MyBlob blob){
//Here your action logic
}

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