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
Related
Not sure how to solve this, need some help here.
Ajax call brings user information to servlet, I save user object in HttpSession and control goes back to Ajax from where i redirect control to next JSP page via controller servlet. However, if i try to retrieve object from HttpSession it is null .. not sure how to solve this issue.
here is my code for firstservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
here is my Javascript / AJAX code to redirect request to nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
and finally control comes to nextservlet - where i would like to process data and then show new JSP page.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
is issue because i am using -> window.location.href = result to send request to nextservlet .. and it goes to doGet??
I am not sure it but I see in Ajax
url: ‘firstservlet’,
type: 'POST'
and control goes to doGet method of nextservlet. It should be nextservlet of post method so use method doPost.
18.12.22
i'm not sure... but try it
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
18.12.26
Javascript
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
Servlet
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
It can read session attribute in doGet Method try it.
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 am getting parse Error
Ajax
$.ajax({
type: "POST",
url: "getStagingImrReport.do",
data: dataString,
dataType: "JSON",
//if received a response from the server
success: function( data, textStatus, jqXHR) { //our country code was correct so we have some information to display
alert(data);
//$("#ajaxResponse").html("<div><b>Country code in Invalid!</b></div>");
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
alert("Something really bad happened " + textStatus);
//$("#ajaxResponse").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#myButton').attr("disabled", true);
},
//this is called after the response or error functions are finsihed
//so that we can take some action
complete: function(jqXHR, textStatus){
//enable the button
$('#myButton').attr("disabled", false);
}
});
controller
public void getStagingImrReport(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
// String policyType = request.getParameter("policyType");
List<String> drop = new ArrayList<String>();
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
final ILoadMgr iLoadMgrRef = (ILoadMgr) getContext().getBean(
IConstants.LOAD);
List<PTypeVO> listVO = iLoadMgrRef
.getPolicyTypes(IConstants.MFFILTER);
for (PTypeVOpolicy : listVO) {
drop.add(policy.getPolicyTypeName());
}
JSONObject jsonObject=new JSONObject();
jsonObject.put("jsonVal", drop);
PrintWriter out = response.getWriter();
System.out.println(" XXXX--------"+drop);
out.println(drop);
out.flush();
} catch (Exception exp) {
Logging.error(
"[LoadController.getpolTypesAjaxDropdown] Exception occured ",
exp);
}
}
Output on console for sysOut
//----XXXX--------[CHIP, County Health Program, Disability, Discount Card, Imputed, Indian Tribe, Mail Order, Medicaid MCO, No Coverage, Other, Rehabilitation, State]
and Jquery alert message shows:
"something really bad happened parse error"
your return type is NOT JSON..its a list or array of string, change your data type or change your return type
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
I am trying to make a simple ajax call. No matter what I do, it always executes the error block. I have a sysout in the doPost that is never hit. Someone please tell me what I am doing wrong. Here is my code.
javascript----
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});
Java----
public class GetBulletAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetBulletAjax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("made it to servlet");
PrintWriter out = response.getWriter();
User user = (User) request.getSession().getAttribute("user");
int userId = user.getId();
List<Bullet> bullets;
BulletDAO bulletdao = new BulletDAOImpl();
try {
bullets = bulletdao.findBulletsByUser(userId);
Gson gson = new Gson();
String json = gson.toJson(bullets);
System.out.println(json);
out.println(json);
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml----
<servlet>
<servlet-name>GetBulletAjax</servlet-name>
<servlet-class>bulletAjax.GetBulletAjax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetBulletAjax</servlet-name>
<url-pattern>/GetBulletAjax</url-pattern>
</servlet-mapping>
What's the URL for your client? Your URL is going to be relative -- so if your page's URL is <server>/foo/bar.html, your ajax request is going to go to <server>/foo/GetBulletAjax. But your servlet definition is <server>/GetBulletAjax.
Change your url in your ajax request to /GetBulletAjax. You need the leading forward slash to tell the browser the resource is located off the root of the site.
in Jquery documentation
http://api.jquery.com/jQuery.ajax/
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
seems that you miss the type attribute which needs to be POST. default is GET as mentioned by documentation. You dont have a doGet in your servlet to support that.
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
type:POST,
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});