Jquery ajax call is not hitting servlet - java

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);
}
});

Related

Java Servlet & jQuery AJAX - unable to retrieve object from session

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.

Unable to get Json object in servlet?

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"
}

getting null `request.parts` posting files to java servlet via jQuery Ajax

here's my js code :
function sendMP3ViaAJAX(MP3File) {
console.log(MP3File.name); //file is present, as I can get its name
$.ajax({type: "POST",
url: "saveMP3",
enctype: 'multipart/form-data',
processData: false,
data: {'mp3File': MP3File},
success: function (text)
{
response = text;
},
complete: function () {
$("#retourAJAX").html("blah blah");
}
});
}
but if I debug my Project
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("MP3FILE"); //request.parts is null...
(constant CHAMP_FICHIER equals the one defined in AJAX call, i.e. mp3File ...) Do you know what's missing ? As I already have dynamically loaded content on the page, I don't want the default HTML POST submit behavior to happen...

No parameters visible in Servlet when contentType is application/json

I am trying a simple program using jquery which makes an ajax request to a Servlet
var searchObject = new Object();
searchObject.search1='abc';
searchObject.search2='xyz';
console.log(JSON.stringify(searchObject));
$.ajax({
url: "SearchServlet",
type: 'post',
data: {data:JSON.stringify(searchObject)},
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
console.log("Posted!!");
}
});
Following is what gets logged on console.
{"search1":"abc","search2":"xyz"}
And in SearchServlet following is the method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameterMap());
Enumeration<String> names = request.getParameterNames();
System.out.println(names.hasMoreElements());
while(names.hasMoreElements()){
System.out.println(request.getParameter(names.nextElement()));
}
}
which prints
{}
false
when contentType specified in the ajax request is 'application/json'
and prints
{data=[Ljava.lang.String;#7eedec92}
true
{"search1":"abc","search2":"xyz"}
when contentType is commented out from the jquery ajax request code.
I would like to understand
why the parameters are not visible when the contentType is
application/json ?
how to access the parameters from request when the
contentType is application/json.
The parameters cannot be used in this case because the post data is not from an HTML Form. Instead you can parse the Json contained in form Data, for example using Jackson :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
try {
// read from stream, convert it to generic class
Map data = mapper.readValue(request.getReader(), Map.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And to use Jackson in a maven project, add this dependency:
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.4</version>
</dependency>
see also other answers on the same subject:
HttpServletRequest get JSON POST data

AJAX error [object,Object]

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

Categories