Servlet POST request using AJAX.
Sending servlet POST request using AJAX causes page refresh and even if the form fields are set to required it is sending the request anyhow and the response is received. The page gets refreshed on clicking OK on the alert window. Also the data is send via url without any encoding (http://localhost:4502/content/auki/test/offerlandingpage.html?name=Candle&description=hello ). How to work around these!
The HTML
<form >
Offer Name:<br>
<input type="text" name="name" required><br>
Description:<br>
<input type="text" name="description">
<br>
<input type="submit" id="submit" value="Submit">
</form>
The JS
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
type: "POST",
url: "/bin/test2",
data: $('form').serialize(),
processData: false,
success: function(resp) {
alert("Name: " + resp.name + " Description: " + resp.desc);
}
});
});
});
The Servlet
package com.auki.core.servlets;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.json.JSONException;
import org.json.JSONObject;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
@Component(service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Test Post Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths="+ "/bin/test2",
"sling.servlet.extensions=" + "json"
})
public class TestPostServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String description = req.getParameter("description");
JSONObject obj = new JSONObject();
try {
obj.put("name", name);
obj.put("desc", description);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
resp.getWriter().write(obj.toString());
}
}
