Send ararylist from js to spring controller - javascript

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?

Related

RequestBody is null in controller

I'm trying to send JSON object from frontend to backend via jQuery AJAX.
The ajax call is performed successfully on the requested path "/survey" with a POST method.
Problem is, my #RequestBody final HmmSurveyForm hmmSurveyForm has null values for my fields "answer1" and "heading".
When I checked request in google chrome developer request is sent:
But the response is null for populated fields from frontend:
I have following code in frontend:
postSurvey: function() {
$.ajax({
url: this.encodedContextPath + "/survey",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: ACC.hmmSurvey.getJSONDataForSurvey(),
async: true,
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("The following error occurred: " + textStatus, errorThrown);
}
});
}
getJSONDataForSurvey: function () {
var json = [];
json.push({"answer1": "1"});
json.push({"heading": "Test"});
return JSON.stringify({"hmmSurveyForm": json});
}
and in backend:
#RequestMapping(value = "/survey", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody HmmSurveyForm postSurvey(#RequestBody final HmmSurveyForm hmmSurveyForm, final Model model) {
System.out.println(hmmSurveyForm);
return hmmSurveyForm;
}
public class HmmSurveyForm {
private String heading;
private String answer1;
// getter, setters
}
You are declaring your RQ body incorrectly in JS
var json = [];
json.push({"answer1": "1"});
json.push({"heading": "Test"});
console.log({"hmmSurveyForm": json});
which has the root hmmSurveyForm as an array of distinct objects, which has no relation to what your backend expects.
You should be using the code below;
var json = {};
json["answer1"] = "1";
json["heading"] = "Test";
console.log({"hmmSurveyForm": json});
Check more on JSON Object in JS here

Javascript AJAX not working on ASP.NET C# and returns a 404

I have a front end code which sends a POST request to the server and returns nothing as the server needs the information.However in Chrome's log i see a 404
Thanks,
Failed to load resource: the server responded with a status of 404
(Not Found)
The following code sends the server a request:
var data = "hi"
var theIds = JSON.stringify(data);
var UrlFixer = '/Process/Complete';
// Make the ajax call
$.ajax({
type: "POST",
url: UrlFixer,
contentType: "application/json; charset=utf-8",
data: { ids: theIds },
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
Backend(C#):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Quiz3
{
public class Process
{
[HttpPost]
public static void Complete(string[] ids)
{
String[] a = ids;
}
}
}
You can get help from the code below to send data.
You do not have to submit a string item in the form { ids: theIds } You must change the form to JSON.stringify(data) .
var data = "Your Name";
$.ajax({
url: '/home/Complete',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
And your class should not be simple. You must have a controller class
Backend:
public class HomeController : Controller
{
[HttpPost]
public void Complete(string Name)
{
//Code ...
}
}
Maybe send your Ids as a list of id and don't stringify your list
public static void Complete(List<T> Ids)
I managed to get this to work with MVC Empty template by the following method:
Firstly a controller is made(inside the controller folder) and its named 'SubmitController'.Now at first i thought that naming it controller at the end is not important but it turns out it is and the URL would be '/Submit' and not '/SubmitController'.
Inside the C# file a function is made and i called it 'Process' with an POST attribute(HttpPost).The URL now would be '/Submit/Process'.In my case i needed to pass an array from the client to server and that is the extra piece of code used in C# to process it and display on the Output page of Visual studio.
SubmitController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class SubmitController : System.Web.Mvc.Controller
{
[HttpPost]
public PartialViewResult Process(string myArray)
{
String[] Items = myArray.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
//print
Items.ToList().ForEach(i => System.Diagnostics.Debug.WriteLine(i.ToString()));
return null;
}
}
}
SendEvent.js
// Make the ajax call
var myArray = data;
$.ajax({
type: "POST",
url: '/Submit/Process',
data: { 'myArray': myArray.join(',') },
});

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 null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

How to send and receive ajax request with parameter in Spring Framework?

I'm try to send a request with ajax but have status 400 bad request.
what kind of data should i send and how to get data in controller?
I'm sure that request is fine only the parameter go wrong
jsp
<script type="text/javascript">
var SubmitRequest = function(){
$.ajax({
url : "submit.htm",
data: document.getElementById('inputUrl'),
type: "POST",
dataType: "text",
contentType: false,
processData: false,
success :
function(response) {
$('#response').html(response);
}
});
}
</script>
controller
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public #ResponseBody
String Submit(#RequestParam String request) {
APIConnection connect = new APIConnection();
String resp = "";
try {
resp = "<textarea rows='10'cols='100'>" + connect.doConnection(request) + "</textarea>";
} catch (Exception e) {
// TODO Auto-generated catch block
resp = "<textarea rows='10'cols='100'>" + "Request failed, please try again." + "</textarea>";
}
return resp;
}
To send an Ajax post request, you could use this :
$.ajax({
type: "POST",
url: "submit.htm",
data: { name: "John", location: "Boston" } // parameters
})
And in Spring MVC the controller:
#RequestMapping(value = "/submit.htm", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String Submit(#RequestParam("name") String name,#RequestParam("location") String location) {
// your logic here
return resp;
}

Categories

Resources