JSP Session Not Recognised In Ajax - ajax

I've tried to put an object in a session inside a servlet and read it inside a javascript code. Actually that works, but after converting the normal javascript code to AJAX, it couldn't recognize it any more.
This is the servlet's code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
}
And I want to recieve it in the following AJAX code.
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = <%=session.getAttribute("json")%>
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>
json content is null.
Any help please?
Thanks very much.

JavaScript executes in the browser. JSP scriptlet executes on the server.
So when you make a request to the page containing the above JavaScript code, the HTML is generated by the server. The server executes the following scriptlet code: <%=session.getAttribute("json")%>. Since, at this moment, the session attribute doesn't exist, the generated HTML is:
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = null
alert(json);
}
}
Then this HTML/JS code is downloaded by the browser, and the JS code is executed in the browser. The browser sends an AJAX request to the server, and when the response comes back, the browser executes the following function:
function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = null
alert(json);
}
}
So obviously, what is displayed in the allert box is null.

You can try like this to have the session object value in javascript.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
PrintWriter out=response.getWriter();
out.write(object.toJSONString());
}
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = ajax.responseText;
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>

Related

Calling API through Ajax - getting 403 error

I am calling an url using ajax - but when it is called I am getting response HTTP/1.1 403
below is my calling code
function callApi() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "http://103.240.91.110/GENCLASS/checkApi.do?
$95599&99&3456790&09012020152103*", true);
xmlhttp.send();
}
Below is the server side method who is sending the response
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward(); // return value
ApiForm apiForm = (ApiForm)form;
try {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
// send back response
System.out.println("true");
}catch(Exception e){
errors.add(ActionErrors.GLOBAL_ERROR, new org.apache.struts.action.ActionError("load.error.unknown"));
//log.error("Critical Error " + e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
forward = mapping.findForward("failure");
} else {
forward = mapping.findForward("success");
}
return (forward);
}
Whenever I am calling the URL I am getting response HTTP/1.1 403
Note that It is working perfectly when I am requesting through browser
I am using tomcat 8.5 on windows on server (called resource)
Any assistance will be appreciated

backbonejs model.save method --post request params become null on the server side

Can anyone tell what am I doing wrong here???
In bankbonejs, I am trying to make a POST request. Here is my code: Im using tomcat server.
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
saveDetails: function (ev) {
var abcDetails= $(ev.currentTarget).serializeObject();
var abc= new ABC();
bank.save(abcDetails, {
success: function (abc) {
router.navigate('', {trigger:true});
}
});
return false;
}
Call goes to the server side (Tomcat) but the post request params are coming as null. I have checked var abcDetails just before requesting the save has the values populated correctly. Also, checked by sending post request thru PostMaster to make sure that values are passed from the client side correctly. However, on the server side these posted request params are null. I am some how stuck here.vAppreciate help in this regard.
Server Side
.
#RequestMapping(value = { "/postedValues" }, method = RequestMethod.POST)
public String getpostedValues( HttpServletResponse response, HttpServletRequest request) throws Exception {
JSONArray jsonarray = new JSONArray();
JSONObject jsonobj = new JSONObject();
String _id = StringEscapeUtils.escapeHtml4(request.getParameter("id"));
String col1= StringEscapeUtils.escapeHtml4(request.getParameter("col1"));
String col2= StringEscapeUtils.escapeHtml4(request.getParameter("col2"));
Also,
Enumeration paramaterNames = request.getParameterNames();
while(paramaterNames.hasMoreElements() ) {
System.out.println(paramaterNames.nextElement());
}--> observation:does not go inside the while loop

XMLHttpRequest request / Servlet response is null

There is a problem with servlet. I send form data by XMLHttpRequest to a server, but servlet handles request object incorrectly and send in response object "null.null". I tried following things but nothing helps:
encode "document.getElementsByName('contractor').value" by encodeURIComponent;
pass the object of FormData as argument to .send();
changing enctype attribute in form to "multipart/formdata";
using get method.
Please take a look. If there are any suggestions how to make it works without using jQuery I would appreciate a lot.
HTML:
<div id="request-form">
<form enctype="application/x-www-form-urlencoded" method="post">
Contractor<input type="text" name="contractor"><br>
Contract No<input type="text" name="contract-no">
<input type="button" onclick=clickOnButton() value="Submit"><br>
</form>
</div>
JS:
var httpRequest;
function clickOnButton() {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
var dataForRequest = 'contract=' + document.getElementsByName('contractor').value + '&contract-no=' + document.getElementsByName('contract-no').value;
httpRequest.onreadystatechange = responseHandler;
httpRequest.open('POST', "/AjaxServ", true);
httpRequest.send(dataForRequest);
}
function responseHandler() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var line = httpRequest.responseText;
alert(line);
}
}
}
Java:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String contractor = req.getParameter("contractor");
String contractNo = req.getParameter("contract-no");
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.write(contractor + "." + contractNo);
}
}
Shouldn't it be 'contractor=' + document.getElementsByName('contractor').value instead of
'contract=' + document.getElementsByName('contractor').value ?

ajax call to servlet and redirect to jsp

Here in the below code i want to call a servlet through ajax and then i redirect the data from servlet to jsp.ajax call to servlet is working fine but the problem is redirecting to the jsp page is not displayed in the browser and the same jsp page is displayed when i used with javascript code without ajax.
javascript ajax code in the jspfile:
function generate(){
...
...
var url="RedirectServlet";
var ajax=new AJAXInteraction(url,"RedirectServlet");
var param ="FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
ajax.send(param);
....
}
function AJAXInteraction(url, actionType) {
this.url = url;
var req = init();
var actionRequested = actionType;
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if(actionRequested=="TestDelegation") {
PostProcess1(req.responseXML);
}
}
}
}
this.send = function(param) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(param);
}
}//end of AJAX Interaction object.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("calling doPost() ");
response.setContentType("text/html;charset=WINDOWS-1256");
String action=request.getParameter("action");
System.out.println(action);
if(action.equals("reports")){
System.out.println("inside reports");
//Getting values from Reports_arb.jsp
String Fromdate=request.getParameter("FD");
String Todate=request.getParameter("TD");
String status=request.getParameter("actionid");
String usercode=request.getParameter("usercode");
//placing given values in a session
request.setAttribute("FD", Fromdate);
request.setAttribute("TD", Todate);
request.setAttribute("actionid", status);
request.setAttribute("usercode", usercode);
//Redirecting to showReport_arb.jsp
//response.sendRedirect("showReport_arb.jsp");
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/sample.jsp").forward(request, response);
You need to understand the fact that when you send http request from ajax, it means that you are sending the request in separate thread and not in the main thread (the page itself from where you are sending the request). So redirection at the servlet will not reflect at the client end. In order to achieve this, send back the URL to which you want to redirect as a response to request and on success method of ajax simply use java script window.location(URL);
At servlet
JSONObject jobj = new JSONObject()
String urlToRedirect = "test.jsp";
jobj.put("url",urlStr);
response.getWriter().write(jobj.toString());
At client end
$.ajax({
url: 'servletName',
data: {
userID: selectedID
},
type: 'post',
success: function(data){
window.location = data.url;
}
});
Instead of creating the request and response object, use jquery Ajax. It is very simple to use.
/* Send the data using post and put the results in a div */
$.ajax({
url: "/YourServlet",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});

AJAX Ready State stuck on 1

Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}

Resources