I'm trying to send json data to servlet using ajax jquery call... below is the code
$(function() {
$( "#mybutton").click(function() {
var testdata = JSON.stringify({
'name': 'name',
'desc':'test'
});
$.ajax({
type: "POST",
url:"/Alert/ReportServlet",
data: testdata,
dataType: "json",
contentType: "application/json",
success : function(data){
console.log("success:", data);
},
error : function(data) {
console.log("error:", data);
}
});
});
});
and the servlet code is
public class ReportingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
System.out.println("The data is" + request.getParameter("testdata"));
}
}
The value is coming as null...Please suggest
In servlet try with
request.getParameter("name");
request.getParameter("dest");
In your Ajax call do something like this
$(function() {
$( "#mybutton").click(function() {
var testdata = JSON.stringify({
'name': 'name',
'desc':'test'
});
$.ajax({
type: "POST",
url:"/Alert/ReportServlet",
data: { d : testdata },
dataType: "json",
contentType: "application/json",
success : function(data){
console.log("success:", data);
},
error : function(data) {
console.log("error:", data);
}
});
});
});
then in java try :
request.getParameter("d");
this you can use some library (like jackson) to convert d into HashMap
Related
My controller :
#RequestMapping(value="/testAdmin", method = RequestMethod.POST,consumes = "application/json")
public ModelAndView testAdmin(#RequestBody Student student) {
System.out.println(student.getName()+" "+student.getId()+" "+student.getLogin()+" "+student.getPassword());
return new ModelAndView("showString","student",student.getName());
}
My ajax function:
function test2(a,ob) {
var student={
id:ob[a].id,
login:ob[a].login,
password:ob[a].password,
name:ob[a].name
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
url: "testAdmin",
data: JSON.stringify(student),
success: function (response)
{
alert("success");
},
error : function(xhr, status, errorThrown) {
alert(status+" "+errorThrown.toString());
}
});
}
Controller method works, but it doesnt go to other page.
I dont know how to fix it, give an example or information to read
I am trying to read a json object that I sent from my ajax to servlet but then I keep receiving null as the value. I tried to log the json object that I am sending from my ajax and it looks fine to me. Can someone tell me what could be my error?
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType:'json',
data:JSON.stringify(obj),
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out= response.getWriter();
String data = request.getParameter("obj");//this is what I get as null
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
}
The json object that I am sending
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}
I'm unable to retrieve the 'values' in my Spring Controller. Can anyone explain what I am doing wrong?
Ajax request
fields[fieldID] = { 'name': fieldName, 'value': fieldValue };
fieldID++;
$.ajax({ url: '/lic/register.html',
data: { 'send': 'login-form', 'values': fields},
type: 'get',
complete : function(){
alert(this.url)
},
success: function( output ) {
alert("success");
},
});
Spring controller
#RequestMapping(value="/register.html", method = RequestMethod.GET)
#ResponseBody
public String suckRegister(HttpServletRequest request,HttpServletResponse response,#RequestParam(value="values", required=false) String[] objectValues) {
System.out.println(objectValues.length); // returning null
}
seems there isn't any need for 'send': 'login-form', unless another request param accepting that value in your controller
Try,
$.ajax({ url: '/lic/register.html',
data: { 'values': fields},
type: 'get',
dataType: "json",
contentType: "application/json",
complete : function(){
alert(this.url)
},
success: function( output ) {
alert("success");
},
});
And your controller should accept
#RequestMapping(value="/register.html", method = RequestMethod.GET)
#ResponseBody
public String suckRegister(HttpServletRequest request,HttpServletResponse response,#RequestParam(value="values[]", required=false) Object[] objectValues) {
System.out.println(objectValues.length); // returning null
}
this is java code ;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String,Object> hsssmap= new HashMap<String,Object>();
hsssmap.put("a","true");
hsssmap.put("b","true");
write(response,hsssmap);
}
private void write(HttpServletResponse response, Map<String,Object> hsssmap) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Gson gson = new Gson();
String json = gson.toJson(hsssmap);
response.getWriter().write(json);
}
Here is js code ;
$(document).ready(function(){
$.ajax({
url: 'uri',
type: 'POST',
dataType: 'json',
data: data,
success: function(data){
$.each (data, function (key,value) {
alert(key+" "+value);
});
},
error: function (e) {
alert("error : " + e);
}
});
return false;
});
success event doesnt work. how to fix it ?
Try to check if the page return some values or not...
try to add alert in success to check it..
try the following
$.post( "uri", function(data) {
alert( "success" + data.a + data.b );
})
if this return you data then your server side servlet working
i have trying to make ajax call with json and below is my code discription
$(document).ajaxStart(function () {
$("#innerpanel").html("<img class='test' src='Image/ajax-loader_clock.gif' alt='loading...' />");});
/* $("#loader").ajaxStop(function () {
$(this).hide();
}); */
$('#btn').click(function(){
testService();
});
function testService(){
name=$("#name").val();
password=$("#password").val();
var testData={name : name,password : password};
$.ajax({
type: "post",
url: "login.do",
data:testData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("madhav");
$("#innerpanel").html("<p1>Welcome</p1> </br>"+"<p1>"+msg.name+"</p1></br><p1> and Your password is "+msg.password+"</p1>");
/* document.writeln("Book id: " + msg.name); */
}
});
}
});
and sever side code is
String userName=request.getParameter("name");
String password=request.getParameter("password");
PrintWriter writer = response.getWriter();
JSONObject obj=new JSONObject();
obj.put("name", userName);
obj.put("password",password);
writer.print(obj);
writer.flush();
But i get null value for both username and password .please help me with example how can I get name and password server side.
if i remove code from request
contentType: "application/json; charset=utf-8",
dataType: "json",
i get name and password value with above server side code.
but how can i do it without removing
contentType: "application/json; charset=utf-8",
dataType: "json",
var testData = {"name" : name, "password" : password};