Pass a form and an array through a single ajax - 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!

Related

jQuery Ajax returns undefined result from asp.net core controller's POST action

Can't make friends out of my AJAX and MVC 6 controller.
This is how I define AJAX call for SetFormValues POST-action:
Index.cshtml
$.ajax({
type: "Post",
url: "Home/SetFormValues",
data: { Name: name, Phone: phone },
dataType: "json",
success: function (result) {
SuccessFunction(result)
},
error: function () {
alert("ALARM!");
},
async: false
})
I see that the controller works and executes SetFormValues action which is defined as the following:
HomeController.cs
[HttpPost]
public JsonResult SetFormValues(string Name, string Phone)
{
string NameErrorStr = string.IsNullOrWhiteSpace(Name) ? "Обязательное поле" : string.Empty;
string PhoneErrorStr = string.IsNullOrWhiteSpace(Phone) ? "Обязательное поле" : string.Empty;
var result = new { NameError = NameErrorStr, PhoneError = PhoneErrorStr };
var jresult = Json(result);
return jresult;
}
Debugger shows that action executes and my resulting JSON object fills correctly:
Finally, his is how SuccessFunction(result) is defined:
Index.cshtml again
function SuccessFunction(result) {
alert("Success function shit executed. result=" +
result + "NameError=" +
result.NameError + ". PhoneError=" +
result.PhoneError);
$("#nameerror").append(result.NameError);
$("#phoneerror").append(result.PhoneError);
}
Function works, alert is raised but result stay 'undefined' no matter what I do:
result = [object Object]
result.val = undefined
Maybe I have to deserialize JSON result properly or fill some properties in it's declaration above, I don't know.
I'm using the lattest libraries for jquery, validate and unobtrusive.
I also tried JSON.parse(result), as it mentioned in the lattest jQuery specification, but it didn't work as well.
Please, help me :)
In asp.net core, by default, the serializer uses camelCase property names for json serialization. So your result will be like this
{"nameError":"some message","phoneError":"some message here"}
Javascript is case sensitive. So use the correct case
$("#nameerror").append(result.nameError);
$("#phoneerror").append(result.phoneError);
For reference : MVC now serializes JSON with camel case names by default
its working perfectly when i have added this line in startup file
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddDbContext<DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DbCrudOperation")));
}
function Edit(id) {
$.ajax({
type: 'GET',
url: "/AjacCrud/EditPahe/" + id,
dataType: 'JSON',
contentType: "application/json",
success: function (response) {
$("#nameEmp").val(response.ID);
console.log(response.ID);
},
error: function (GetError) {
alert(GetError.responseText);
}
});
};

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!

Ajax call fails to receive a list of objects from controller action method

Here is my controller
[HttpPost]
public JsonResult UpdateCountryDropDownList(string ContinentId)
{
HotelContext H = new HotelContext();
int ContinentID = int.Parse(ContinentId);
List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentID).ToList();
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
return Json(new { ListResult = Co }, JsonRequestBehavior.AllowGet);
}
When I pass mylist instead of Co it work
And here is my ajax call.
$(document).ready(function () {
$("#Name").change(function () {
var ContinentoId = $(this).val();
$.ajax({
type: "Post",
dataType: "json",
data: { ContinentId: ContinentoId },
url: '#Url.Action("UpdateCountryDropDownList","Home")',
success: function (result) {
alert("worked");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("failed");
}
It give my failed message when passing list of country object but success when passing list of strings. What is going wrong here?
First thing you should do is inspect WHY your call failed.
Instead of doing alert('failed') do something like console.log(arguments) and look at your browsers dev tools (console) to find the actual message.
I would hazard a guess that your error message would be along the lines of no method exists.
Your controller is only setup to receive a single string.
public JsonResult UpdateCountryDropDownList(string ContinentId)
If you want to be able to POST a list of string, then change your controller to accept a List<string>, such as (note i changed the name of the parameter)
public JsonResult UpdateCountryDropDownList(List<string> ContinentIds)
You will then be able to post an array of strings - adjust your ajax call to something like:
data: { ContinentIds: ["1","2","3"]}
None of this is tested, though the concept is there.

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

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