Sending an javascript array to a servlet - java

Hello I have been looking at other threads like mine and I can't seem to get my code working!
I need to send the JS array containing ints to a servlet this is current code:
Javascript code:
function sendReminderEmails(){
$("#sendReminderEmails").click(function(){
var people = null;
var peopleBatch1 = null;
$.ajax({
type: "POST",
url:"getAllUnregisteredPeople",
async: false,
success: function(data){
people =JSON.parse(data);
}
});
peopleBatch1 = people.splice(0,200);
$.post("sendReminderEmails", {people:peopleBatch1, mode : "insert"} , function(data){
});
});
}
Servlet Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response){
String peopleIDs[] = request.getParameterValues("people");
}
It keeps returning null! Can someone tell me if I am doing something wrong ?

You must use JSON.stringify to send your JavaScript object as JSON string.
Change your code
var obj = { people: peopleBatch1, mode: "insert" };
$.post("sendReminderEmails",JSON.stringify(obj) , function(data) {});
On Servlet side you need you use
String jsonStr = request.getParameter("people");
then Convert this jsonStr to JSON object.

in "$ajax" you need to pass the required parameter, eg
var myArray={'john', 'paul'};
$.ajax ({
type: "POST",
url:"getAllUnregisteredPeople",
data: {people: myArray}
async: false,
success: function(data) {
people = JSON.parse(data);
}
});

Related

Error javax.json.stream.JsonParsingException: when making an AJAX API call

I have developed a web based program using java jersey in my back end and jsp in my front end. When I make a post API call using Ajax my back end gets the following exception.
javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)
I guess it's something wrong with the data which I'm passing through the Ajax API call.
Here is my ajax API call:
var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: obj,
dataType: 'json',
success: function () {
alert("successed");
}
});
This is my back end implemented code:
#Path("testing")
public class test {
UserRepository userRepo=new UserRepository();
#Path("users")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
userRepo.createUser(a);
return a;
}
}
You should send the data as a JSON String, not a JSON Object. Avoid the JSON.parse from your code.
var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';
Alternatively, I would construct the JS Object, and apply JSON.stringify on it. This way, the code is more readable:
var data = {
userName: "John",
password: "hgvv",
img: "New York",
fname: "kjbjk",
lname: "bkbkkj",
tp: "buhb",
address: "jhbjhb",
type: "user"
};
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: JSON.stringify(data), // added JSON.stringify here
dataType: 'json',
success: function () {
alert("successed");
}
});

How to read two json objects in spring boot controller

I am new to java, i am trying to pass two json objects from ajax call to controller class... but i am getting below exception
Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.controllers.EmployeeController.saveData(java.lang.String,com.entities.EmployeeData,org.springframework.validation.BindingResult)
Jquery Code:
$("#saveData").submit(function(event) {
var data = [];
var formData = {};
var myJsonString;
var slab, lower;
$("table tbody tr").each(function(index) {
//alert(index);
slab = $(this).find('.slab').val();
lower = $(this).find('.lower').val();
if(slab != undefined && lower != undefined){
var form1 =new Object();
form1.slab=slab;
form1.lower=lower;
data.push(form1);
}
});
var form = this;
event.preventDefault();
$.each(this, function(i, v){
var input = $(v);
formData[input.attr("name")] = input.val();
});
var url = "/Portal/SaveData";
ajaxCall(url,formData,data);
});
function ajaxCall(url,formData,data){
//alert("AjaxPost!!!"+url);
// DO POST
$.ajax({
type : "POST",
contentType : "application/json",
url : url,
data : JSON.stringify({formData:formData,value:data}),
dataType : 'json',
beforeSend: beforeSendHandler,
success : function(response) {
alert("Success");
}else{
alert("else");
}
},
error : function(e) {
bootbox.alert({
size: "small",
title: "ALERT",
message: "There seems to be some problem while Proccessing record!"
})
}
});
}
Controller Method:
#RequestMapping(value = "/SaveData", method = RequestMethod.POST)
public #ResponseBody String saveData(#RequestBody String value,#Valid #RequestBody EmployeeData emp, BindingResult result) {
System.out.println(" Creating!!!");
//logic here
}
Where is the mistake in ajax call or in controller file?
there is any other way to pass multiple json objects to controller class file?
The #RequestBody annotation is expected to map to one and only one parameter in your method and to contain the entire contents of the incoming request.
You should map all your form data into a single JSON object, then handle that as a single JSON object in the backend as well.

Return value from JAVA API Value

On the click of a button I am sending a JSON to the Java Server side via an API POST call.On validating the JSON, the server side function return a String.
How do I access that string on my JavaScript client side?
That String will tell me whether the JSON is valid or not.
You can use parseJSON(json) function in jQuery, for example:
function getValue(actionName) {
$j.ajax({
url: actionName + ".do",
data: {
"action" : "getJsonValue"
},
dataType: "json",
success: function(response) {
if (response.errorCode) {
showErrorMessage(response.errorMessage);
return;
}
response = $j.parseJSON(response);
return response;
},
});
}

Returning Hashmap From controller to JSP in Springmvc

I have two dropdownlists in Jsp One for state and other for country. As soon as i select country the statelist should be populated automatically with respective lists. But i am getting whole jsp page as response in ajax call.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My controller program
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public ModelAndView showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, Model model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
if (country.equals("UnitedStates")) {
stateMap.put("Al","Alaska");
stateMap.put("Tl","Texas");
} else if (country.equals("UnitedKingdom")) {
stateMap.put("Be","Bedfordshire");
stateMap.put("Ber","Berkshire");
} else if (country.equals("India")) {
stateMap.put("Mh","Maharashtra");
stateMap.put("WB","West Bengal");
stateMap.put("KR","Karnataka");
stateMap.put("AP","Andhra Pradesh");
stateMap.put("TN","Tamil Nadu");
}
return new ModelAndView("LoginForm","state" ,stateMap);
}
I am using spring form. I need to get only Staemap as respone but i am getting whole jsp page as response.
I need to get only Staemap as respone but i am getting whole jsp page
as response.
Because you are returning the ModelAndView object with the view here,
return new ModelAndView("LoginForm","state" ,stateMap);
If you need to return the respone alone from the controller method.However you cant print the HashMap directly in the ajax response on your jsp. IMHO you can convert it to JSONArray
JSONArray jarray = JSONArray.fromObject(statemap);
Read ,
send array from controller to a view using JSON in MVC
Sending JSON response from spring controller
loop through json array jquery
#RequestMapping(value="LoadBaselineVersions")
#ResponseBody
public Map<Integer,String> loadBaseNames(#RequestParam(value="projectname") String name,HttpSession session){
return basenameService.getBaselineversions(name);
}
$("#projectname").bind(
'blur',
function() {
$.ajax({
type : 'post',
url : 'LoadBaselineVersions?projectname='
+ $("#projectname").val(),
dataType : 'json',
success : function(data) {
$("#baseversion").empty();
$.each(data, function(val, text) {
$("#baseversion").append(
$('<option></option>').val(text).html(
text));
});
}
});
});

get json array from servlet using ajax

I have to json array in my servlet.
I want to fetch json array value and print in to jsp page using ajax.
below is code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
jsp
I got error msg here.
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
error : function() {
alert("Error");
},
success : function(data) {
alert(data);
}
});
See, if you want to pass that from servlet to jsp you need not to make a request (ajax), since servlet and jsp both exists at server side.You just set that json array as a request attribute or session attribute and get it in jsp and display(with loop).NO need of ajax there.
If You need to fetch the data with synchronous call:
In servlet
PrintWriter out = response.getWriter();
out.println(htags);
I won't clutter SO with another full example,see this SO post:How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?
Try this
servlet code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String jsons = "["+htags+","+trends+"]"; //Put both objects in an array of 2 elements
out.print(jsons);
and on you jsp page
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
contentType:"application/json",
error : function() {
alert("Error");
},
success : function(data) {
var data1=data[0],
var data2=data[2],
alert(data1[0]);
}
});
Servlet can use this to send json array or json object to client.
JSONArray jsonArray = [{:}, {:}];
response.getWriter.write(jsonArray.toString());
In JSP page, this method call the request JSON to Servlet and catch the json array or json object with annonymous function(JSON.parse is used to convert string to json object or json array) method.
$("button").click(function(){
$.get("ServletToJSP",function(data,status){
alert("Data: " + JSON.parse(data) + "\nStatus: " + status);
});
});
in servlet:
String uri = request.getRequestURI();
if (uri.equalsIgnoreCase(uri)) {
response.setContentType("application/json");
/* get the json array */
response.getWriter().write(array.toJSONString());
}
jquery:
$('#buttonid').on('click', function() {
var url="your url";
$.ajax({
type : 'POST',
url : url,
data : null,
error : function(xhr, status, error) {
alert("error");
},
success : function(data) {
alert("success");
$.each(data, function(key, val) {
console.log(val);
}
});
});

Categories