My knowledge of Spring boot is very low.
I have made a table in HTML, which when I click on, an event is sent to a Javascript function, in which I try to catch the Id (a string) of the cell and send it to the controller. I tried many examples from internet but none worked for me, can anyone help me please?
The id is being caught correctly by mouse click, but I have a problem with sending.
This is my JSP
<c:forEach items= "${rooms2}" var="m" >
<tr>
<td style="background-color:OldLace">${m.day }</td>
<c:choose>
<c:when test="${m.hour1confirm==false}">
<td style="background-color:green" id="${m.hour1}" onclick=
"content(this)" >${m.hour1 }</td>
...
<script >
// <script type="text/javascript">
function content(elem)
{
// $(document).ready(function()
// {
// // PREPARE FORM DATA
// var idt =elem.id;
// console.log(idt);
// // DO POST
// $.post({
// type : "POST",
// url :"reservation2",
// // contentType: "application/json",
// data : JSON.stringify(idt),
// dataType : 'json',
// })
// });
var idt =elem.id;
console.log(idt);
$.ajax({
url:"reservation2",
type: 'POST',
data: idt,
dataType: "text",
contentType: false,
mimeType: false,
success: function(response){
console.log(data);
return false;
}
});
}
</script>
this is controller
.
.
.
// #RequestMapping(value = "/reservation2", method = RequestMethod.POST)
// public String reservation2(#ModelAttribute("idt") String idt , Model model) {
// return "Reservation2";}
#RequestMapping(value = "/reservation2", method = RequestMethod.POST)
public #ResponseBody
String Submit(#RequestParam("idt") String idt) {
// your logic here
return "reservation2";
}
#RequestMapping(value = "/reservation2", method = RequestMethod.GET)
public String reservation(Model model) {
List<Room> rooms2= new ArrayList<>();
System.out.println(rooms2);
rooms2= x.findAll();
model.addAttribute("rooms2", rooms2);
return "reservation2";
...
when I run I get this error in console :
POST http://localhost:8080/reservation2 403 ()
I believe you are not sending the right parameter along the way. When you do the ajax post request, in the field data can you specify the name of the parameter you are sending?
Can you try this one
$.ajax({
url:"reservation2",
type: 'POST',
data: {"idt": idt},
dataType: "json",
contentType: "application/json",
success: function(response){
console.log(data);
return false;
}
});
Try changing your request to something like this
$.ajax({
url: "/reservation2", //added '/' in the beginning
type: 'POST',
data: idt,
dataType: "text",
contentType: "text/plain", //change
//mimeType: false, //remove
success: function(response) {
console.log(data);
return false;
}
});
and your controller to this
#RequestMapping(value = "/reservation2", method = RequestMethod.POST)
public String reservation2(#RequestBody String idt)
{
// your logic here
return "reservation2";
}
Related
I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",
I am trying ajax Javascript Map, to spring controller. but it's getting null in backend. Please excuse if i am repeating question.
I can't change Map type, as my whole front end logic on it. Because set, get and has method from Map is what I need.
var ansMap = new Map(); // This way i created object
// added many values in ansMap,
$.ajax({
type: "POST",
url: myUrl,
contentType : 'application/json',
//cache: false,
dataType : 'json',
data : ansMap, // can't JSON.stringy(ansMap) as it gives empty json
success: function(result) {
console.log(result);
},
Spring code
#RequestMapping (value="myUrl", method=RequestMethod.POST)
public #ResponseBody String saveData(#RequestParam(required = false, value = "mapData") Map<String,List<String>> mapData, Model map)
{
log.info("Call Success");
log.info("mapData: "+mapData);
Please suggest what needs to be done here.
You can actually send your Map without mutating the value
var ansMap = new Map(); // This way i created object
// added many values in ansMap,
$.ajax({
type: "POST",
url: myUrl,
contentType : 'application/json',
//cache: false,
dataType : 'json',
data : JSON.stringify(Object.fromEntries(ansMap)), // can't JSON.stringy(ansMap) as it gives empty json
success: function(result) {
console.log(result);
},
That will turn it into a javascript object.
Object.fromEntries Will turn you Map into a javascript object, without altering the original Map
Regarding your backend i think you mis-interpret the #RequestParam annotation
The #RequestParam is to extract query parameters, form parameters and even files from the request.
I think that what you are looking for is #RequestBody.
Meaning you would be looking for something similar to :
#RequestMapping(value="/myUrl",method = RequestMethod.POST)
public String saveData( #RequestBody Map<String,Object> body) {
This should work
page
<button id="doPost"> post </button>
<script>
$(function () {
var map = new Map();
map.set('CIQ_2','aa');
map.set('CIQ_3','78965412300');
console.log(map);
$("#doPost").click (function() {
var settings = {
beforeSend: function(xhr, options) {
xhr.setRequestHeader("content-type" ,"application/json; charset=utf-8");
},
type: 'POST',
url: '/post' ,
data: JSON.stringify(Object.fromEntries(map))
}
$.ajax(settings).done(function(result) {
console.log("done : " + result);
});
});
});
</script>
Controller
#PostMapping("/post")
#ResponseBody
public String post(#RequestBody Map<String,String> data) {
System.out.println(data);
return "data well received";
}
will print
{CIQ_2=aa, CIQ_3=78965412300}
working code on GitHub
I'm trying to post a value and a string[] to Spring MVC. I either get:
HTTP Status 400 - Required String[] parameter 'testCaseNames' is not present
If I turn it to a list:
HTTP Status 400 - Required List parameter 'testCaseNames' is not present
What type should I put then??
var flowName = $('#flowName').val();
var testCaseNames = [];
$('.icons-right .action-icon:first-of-type').each(function() {
testCaseNames.push($(this).attr('name'))
});
console.log(testCaseNames);
$.ajax({
type: 'post',
url: '/create-flow/save',
data: {
flowName: flowName,
testCaseNames: testCaseNames
},
success: (function (result) {
})
});
#RequestMapping(value = "/create-flow/save" , method = RequestMethod.POST)
public #ResponseBody String saveFlow(HttpSession session, #RequestParam("flowName") String flowName, #RequestParam("testCaseNames") String[] testCaseNames)
{
String user = session.getAttribute("loggedUser").toString();
return TestFlow.addFlow(flowName,testCaseNames,user);
}
Output in console:
["sdad", "xzxc"]
You are posting the data as body of your REST request.
$.ajax({
type: 'post',
url: '/create-flow/save',
data: {
flowName: flowName,
testCaseNames: testCaseNames
},
success: (function (result) {
})
});
But in your controller you are recieveing as RequestParams.
#RequestParam("testCaseNames") String[] testCaseNames
That is the problem.
RequestParams are part of your url. For example if your url is like
http://blahbla:1234?abcd=1234&defg=5677
then abcd and defg are request parameters.(This is one way to send data)
Another way is to set the data in the Message Body which you don't see in the url, like how you are doing now.
You have two options to fix this
1. Change your ajax request to remove the data part and include testCaseNames and flowName in url like this
$.ajax({
type: 'post',
url: '/create-flow/save?flowName='+flowName+'&testCaseNames='+testCaseNames,
success: (function (result) {
})
});
2. Change your controller by removing the requestParams and creating a class with testCaseNames and flowName as fields and accept that as argument.
#RequestMapping(value = "/create-flow/save" , method = RequestMethod.POST)
public #ResponseBody String saveFlow(HttpSession session, #RequestBody SomeClass someclass)
{
.....
}
class SomeClass {
String flowName;
String testCaseNames; // Field Names should match exactly with what you send from frontend
// Gettter & Setters
}
You can try as follow
#RequestMapping(value = "/create-flow/save" , method = RequestMethod.POST)
public #ResponseBody String saveFlow(HttpSession session, #RequestParam("flowName") String flowName, #RequestParam("testCaseNames[]") String[] testCaseNameValues)
{
String user = session.getAttribute("loggedUser").toString();
return TestFlow.addFlow(flowName, testCaseNameValues,user);
}
And also add "[]" to Javascript field name
$.ajax({
type: 'post',
url: '/create-flow/save',
data: {
'flowName': flowName,
'testCaseNames[]': testCaseNames
},
success: (function (result) {
})
});
The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept
I have a view with a partial view in it. I have a model in the view and a kendogrid in the partial view. I also have an ajax call to teh controller just updates my model without returning a view. Say I need to click a toolbar button on the grid that generates an id. Now i want to return that id to the view(by updating model with that id). But success(data) is not firing
$.ajax({
type: "POST",
data: JSON.stringify({ Id: pId, schId: sId}),
contentType: "application/json; charset=utf-8",
dataType: "JSON",
cache: false,
url: '#(Url.Action("Process", "Controller"))',
success: function (data) {
var abc = data.InvoiceId;---->not fired
},
});
Controller
public ActionResult Process(int Id, int schId, SearchModel mymodel, [DataSourceRequest]DataSourceRequest request)
{
int myId = -1;
// generate the Id);
myId = generatenewId(Id,schId);-- this gets generated and myId is updated
}
mymodel.Id = myId
return View(mymodel)
}
You should decide wether you want to send a HTML result (view), or JSON result (Json), and call the corresponding result in your Action. If you set the dataType to JSON in your jQuery Ajax call, you should return Json result, for example:
public ActionResult Process(int Id, int schId, SearchModel mymodel, [DataSourceRequest]DataSourceRequest request)
{
int myId = -1;
// generate the Id);
myId = generatenewId(Id,schId);-- this gets generated and myId is updated
mymodel.Id = myId
return Json(mymodel) // this will return Json in the response containing your model object
//return View(mymodel) !!! This would return a full HTML response rendered with you model
}
This is how I do it using a mail form!
Look at the signature in my controller I use JsonResult not ActionResult!
Also I return JSON not a View!
return Json(result);
IN MY CONTROLLER
public JsonResult AjaxMailer(MailerModel model)
{
Emailer mailer = new Emailer();
JsonResult Jr = new JsonResult();
string result = mailer.DispatchEmail(model.phone, model.name, model.message, model.email);
return Json(result);
}
JAVASCRIPT IN MY VIEW
function imClicked(e) {
e.preventDefault();
var messageObj =
{
"name": "",
"email": "",
"phone": "",
"message": "",
};
messageObj.name = $("#name").val();
messageObj.email = $("#email").val();
messageObj.phone = $("#phone").val();
messageObj.message = $("#message").val();
$.ajax({
dataType: "json",
contentType: 'application/json',
type: 'POST',
url: '/Contact/AjaxMailer',
data: JSON.stringify(messageObj),
error: printError,
success: mailsent
});
};