How to pass data from Spring controller to JQuery $.post() call - javascript

After posting data from the Jquery $.post() method, I am attempting to return some data which I want to use in the Jquery alert() from a Spring boot 1.5.1 controller method. Currently, the returned data is empty when used in the alert().
Jquery:
$('#element').click(function() {
var formData = $('#element').serialize();
var posting = $.post( '/update.json?id=${item.id}', formData );
posting.done(function( data ) {
alert(data);
});
return false;
});
Controller:
#RequestMapping("/update.json")
#ResponseBody
public void update(HttpServletRequest request,
Map model,
#RequestParam(value="id", required=true) Integer id) {
// to validation and binding...
model.put("result", "test");
}
Why is the result property not accessible in the Jquery data object in the callback?

Your Controller has a return type as void, that's normal. You can either use a response entity, if you want to set the status:
return new ResponseEntity<String>("test", HttpStatus.OK)
or you can return a plain string a well.

Related

Is it possible for a Java controller to pass an attribute to a success ajax call?

As the title says, I want to pass a variable from a controller to a success ajax call function but is it possible? For example:
I have a Java class with a controller like this:
#RequestMapping(value = "checkFruit", method = RequestMethod.POST)
#ResponseBody
public ModelAndView checkFruit(HttpServletRequest request, String fruitInput) {
ModelAndView modelAndView = new ModelAndView();
if (fruitInput.equals("apple")) {
modelAndView.addObject("fruitType", 1); //This is what I want to pass to the success ajax call.
} else if (fruitInput.equals("orange") {
modelAndView.addObject("fruitType", 2); //This is what I want to pass to the success ajax call.
}
modelAndView.setViewName("fruitGarden");
return modelAndView;
}
And a jsp view with an ajax call like this:
$("#checkFruitBtn").click(function () {
var fruitInput = $("input[name=fruitInput]").val();
$.ajax({
type: 'POST',
url: 'checkFruit',
data: 'fruitInput=' + fruitInput,
success: function () {
var fruitType= ${fruitType}; //I want to get the attribule of that "fruitType" variable set in the controller. But this is where things went wrong.
if (fruitType == 1) {
alert("This is an apple.");
} else if (fruitType == 2) {
alert("This is an orange.");
}
window.location.href = "/someURL";
}
});
});
In the above example. When I click the button "checkFruitBtn", it will send an ajax call to the controller "checkFruit". And in this controller, I'll set a variable "fruitType" to send it to the success ajax call function. In this success ajax call function, I'll get the value of the "fruitType" variable to check it and show alert message according to its value... But, things aren't going as planned.
My question is, is there a possible way of getting the value of that "fruitType" variable? I've searched for a getting method but I still can't find one that fitted in my case. I'm terribly sorry if this question have been asked before.
Thanks in advance!
With annotation #ResponseBody, Springmvc converts the returned object to a response body by using an HttpMessageConverter.
ModelAndView usually involves command object and view name.
so you can use ModelAndView with a Jsp page , then use el to evaluate command object values. to use #ResponseBody, Springmvc only return strings.
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
var x= g.fruitType; //Now you can do the operation based on the output.

How do I make AJAX grab the data from the controller in MVC?

So, I have this AJAX call and what I want to do is for the controller to return the string as a JSON object back to the view where my ajax call is. Now here's the thing. I don't know how to do it and which class would help me do it. Everything I've tried doesn't work at all. My question is when I use the $.post method how do I make AJAX "grab" the data back from the controller?
Since people comment on my Javascript, I don't mind that, I'll fix it later. The question is
How do I return anything I want from the controller in MVC? The controller is where I need help
Here's my call:
<script>
$(document).ready(function () {
alert("document ready");
// Attach a submit handler to the form
$("#searchForm").submit(function (event) {
alert("submitsearchForm");
//event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
query2 = $form.find("input[id='query']").val(),
url = "/umbraco/Surface/SearchDictionarySurface/HandleDictionarySearching/";
alert("query2" + query2);
// Send the data using post
var posting = $.post(url, { query: query2 });
alert(url);
//Put the results in a div
posting.done(function (query2) {
var content = //bla bla bla;
$("#result").empty().append(content);
alert(query2);
});
});
});
</script>
Also, I'm using Umbraco. That's why the surface controller:
using MyUmbraco.Models;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
namespace MyUmbraco.Controllers
{
public class SearchDictionarySurfaceController : SurfaceController
{
// GET: SearchDictionarySurface
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult HandleDictionarySearching(string query)
{
if (!string.IsNullOrEmpty(query))
{
var query2 = Json.parse(query);
//return Json object????
//I NEED HELP HERE
}
else
{
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
}
}
}
}
So, to any newbies out there that might need the help I needed (and because I've been looking for this thing for AGES and nobody responds, here's how you do it:
Your JQuery callback function, and your controller must have the same variable. E.g:
Controller:
public JsonResult ExampleName(string query)
{
if (!string.IsNullOrEmpty(query))
{
//YOUR CODE HERE
return Json(yourDataHere);
}
else
{
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
}
}
And JQuery callback function:
posting.done(function (data) {
//your callback function here
});
That's the trick for JQuery to know what to "grab" from the controller when it returns it. Make sure you return Json(yourDataHere). In case you're wondering, yes, just write 'data' in the function and it will grab yourDataHere from the controller, by itself.
Also, make sure you either have the AntiForgeryToken in both your form and your controller or in none of them. If you have it in your controller only, it will not let you control everything through JQuery.
There is some issues in your javascript.
Try to follow this pattern :
posting.done(function (response) {
var JSONData = JSON.parse(response);
// do something with your json
// ....
// Then append your results in your div.
$('YOUR DIV SELECTOR').html(THAT YOU WANT TO DISPLAY);
});
If you want to return objects and JSON, use a WebAPI controller rather than a surface controller, which will just return an ActionResult. You can get a Surface controller to return JSON, but you'd be better off using an API controller, as that will return JSON objects by default, which is what I assume you're after?
Here's some documentation for WebAPI controllers!

Using ajax to update list.

I am currently trying to update a list of duties after the user has posted a new duty. I am trying to use Ajax doing this. However I am not shure how to use ajax for posting to my controller and then add to my list. How do I use my datafield in my ajax method and how do I update my list?
My controller:
[HttpPost]
Public ActionResult CreateDuty(PartialViewModel d)
{
db.DutiesTable.Add(d.OneDuty);
db.SaveChanges();
pv.DutyList = db.DutiesTable.ToList();
return View("Index");
}
My Ajax method:
<script>
$('#getDuty').click(function () {
$.ajax({
type: 'POST',
url: "/Home/CreateDuty",
data: {d : d}
}).success(function (data) {
alert(data + status);
});
});
</script>
Not enough information.
Where did d come from and what is it (javascript).
For your EF code I assume DutiesTable does NOT contain PartialViewModel's so there is a mapping that needs to happen there between the view model and EF model classes.
[HttpPost]
Public ActionResult CreateDuty(DutyViewModel d)
{
Duty newduty = new Duty(){ /*map values from d to fields here*/}
db.Duties.Add(newduty);
db.SaveChanges();
return View("Index");
}
Once you have your data posting over the controller and saving with EF you need to decide on if your javascript needs a copy of the updated entity (mapped back to a PartialViewModel most likely or if a simple success/fail message is enough and do what it needs to on that side.
I don't know what you mean here: "and then add to my list" - what list?

WebForms GET Json requests (JsonRequestBehavior.AllowGet)

I have an old WebForms project that needs revisiting and I want to add some new features.
I want to load the data using $.getJSON(), this is very simple in ASP.NET MVC because you can return the data like this,
return Json(data, JsonRequestBehavior.AllowGet);
The Get doesn't work in WebForms,
// Http GET request
$.getJSON('Attributes.aspx/GetAttributes', { 'ProductId': '3' }, function (d) { alert(d); });
The Post works.
// Http POST
$.post('Attributes.aspx/GetAttributes', { 'ProductId': '3' }, function (d) { alert(d); });
Here is the WebForms WebMethod,
[WebMethod]
public static string GetAttributes(string ProductId)
{
List<QuoteAttribute> list = DAL.GetAttributes(ProductId);
var json = JsonConvert.SerializeObject(list);
return json;
}
I want to return json using the GET method.
Is there an JsonRequestBehavior.AllowGet for WebForms?
Any help is appreciated.
Thanks
Need to add "[ScriptMethod(UseHttpGet = true)]" before the method.This will allow GET method.
eg.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetAttributes(string ProductId)
{
List<QuoteAttribute> list = DAL.GetAttributes(ProductId);
var json = JsonConvert.SerializeObject(list);
return json;
}

how can pass array to java servlet

On my jsp, this is my code :
$('.save').on("click",function(){
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
var data = JSON.stringify(array);
$.post("Controller.html", data, function(response) {
/// i dont know what to put here,so i think this where i get trouble with
});
});
but still data is null when i check on servlet.
this is my servlet :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data=request.getParameter("data");
if (data== null) {
System.out.println("null");
}
RequestDispatcher view = request.getRequestDispatcher("/page.jsp");
view.forward(request, response);
}
fiddle here
First you need to send the data, you can use an ajax post method:
$.post("yourservlet", data=JSON.stringify(array), function(response) {
// handle response from your servlet.
alert(response)
});
In servlet, you retrieve the data with the command:
String data=request.getParameter("data");
Then you need to parse the json, you can use a library like JSON simple:
Object obj = JSONValue.parse(data);
JSONArray array = (JSONArray) obj;
Or you can manually parse it. Based on your code, your json string will look like this:
data = "[{'orange':['1.00','5']},{'apple':['2.00','5']}]";
You can use split() method or StringTokenizer to separate each object, but you should write your own parser method, for this you can find many tutorials on google.
Javascript is in client-side. And java servlet is for server-side.
You must use ajax to make a call from client-side to your servlet.

Categories

Resources