I want to fetch object from servlet.
I try below code but I get "[object Object]" . I want "Description" value.
I got out in browser when I run http://www.host.com/f/ServletToJSP1/*
o/p {"Description":"Nutanix provides disruptive datacenter infrastructure solutions that are hyper-efficient, massively scalable and elegantly simple."}
in console log :Uncaught ReferenceError: google is not defined
How can I do that ?
jsp code
$.ajax({
url : 'ServletToJSP1',
type : 'GET',
dataType : 'json',
success : function(response) {
//response = $.parseJSON(response);
alert(response);
},
error : function(error) {
//error handling....
alert(error);
}
});
servlet code
JSONObject objTw = new JSONObject();
objTw.put("Description", "Nutanix provides disruptive datacenter infrastructure solutions that are hyper-efficient, massively scalable and elegantly simple.");
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
out.println(objTw);
Access the description property on the response object.
$.ajax({
url : 'ServletToJSP1',
type : 'GET',
dataType : 'json',
success : function(response) {
//response = $.parseJSON(response);
alert(response.Description);
},
error : function(error) {
//error handling....
alert(error);
}
});
Are you developing in Chrome?
You can open the dev tools with CTRL+SHIFT+I then open the Console.
Instead of alert(respone) try console.log(response) to have a deeper look into the variable.
Try
success : function(response) {
alert(response[0].Description);
},
and in your servlet code try to add out.flush();
Related
My requirement is to submit a HTML form (Including File Type and Text Type) using AJAX call, I am using Struts-1 at the server side to parse the http request. Below is the code i have wrote, but its giving me exception when i try to print the name of the file.
JavaScript Code :-
function saveUpdateRfc(formId) {
console.log("Enter in Upload Script");
var formData = new FormData();
formData.append("file",formId.files[0]);
console.log(formData);
$.ajax({
url : "AddRfc.do",
type : "POST",
data : formData,
async: false,
cache: false,
mimeType:"multipart/form-data",
contentType: false,
processData: false,
success : function(result) {
if (result.result == "success") {
console.log("Rfc Added");
} else {
bootbox
.alert("Some Error Occured While Opening this Rfc. Please refresh the page and try again.If this Problem Persists, please report it to dev team.");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
bootbox
.alert("Some Error Occured While Opening this Rfc. Please refresh the page and try again.If this Problem Persists, please report it to dev team.");
},
complete : function() {
}
});
}
At Server Side, Here is the java code to get the file from the form.
RfcLogBean log = new RfcLogBean();
log = (RfcLogBean) form;
FormFile uploadedTakeoffSheet = log.getMyFile();
System.out.println("======= " +uploadedTakeoffSheet.getFileName());
System.out.println("======= " +uploadedTakeoffSheet.getContentType());
Can someone please help.!!
I have a java function that gets a JSON string of data from a Servlet in Java. I am trying to use that data to populate a datatable (http://www.datatables.net/examples/data_sources/ajax.html)
This is the way that the DataTables website instructs users to populate datatables:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
And this is the javascript method that calls the doPost method in my servlet to generate and return the JSON:
<script>
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
//$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}
}).responseText;
console.log(bodyContent);
});
</script>
How can I get the JSON string in var bodyContent to populate the datatable?
First off, you're not really doing AJAX; when you do:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}).responseText;
You set async: false ... but AJAX stands for Asynchonous Javascript and XML. With an AJAX approach the following happens:
You start the request by doing $.ajax
The server takes however long to respond; the user's browser is not locked up during this time
When the server responds the success callback you defined gets called
With your approach
You start the request by doing $.ajax
The user's browser is locked up while waiting for a response
When the server responds your code (after the $.ajax call) is invoked.
To make your code actual AJAX do this instead:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(responseText) {
bodyContent = responseText
}
});
Of course, once the response comes back you also need to build your Data Table, so what you really want is:
success : function(responseText) {
$('#example').dataTable( {
"data": responseText
});
}
(Or something to that effect; I forget DataTable's exact syntax.)
Refer to jQuery.ajax docs. The data returned from server in first argument of success callback. Also note that all manipulations with this data whould be inside this callback. I guess you should additionally check status argument:
$(document).ready(function() {
var bodyContent = null;
$.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(data, status) {
console.log(data);
$('#example').dataTable( {
"data": $.parseJSON(data),
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
]
});
});
});
});
UPDATE To populate data server should respond with JSON encoded array of data and you should parse it and pass to dataTable as it noted here.
I am using jQuery/AJAX call to pass control to servlet and upon success sending control to another servlet. Not sure how can I retrieve JSON object set by first sevlet to second. Here is my pseudo code.
orders.jsp
---------------
// display orders
// on click calls following ajax
$.ajax({
url : "processorder",
type : "POST",
dataType : "text",
data : formData,
success : function(data, textStatus, jqXHR) {
var successUrl = "checkout"; //upon success pass the control to checkout.java
window.location.href = successUrl;
return false;
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Oops ! Error occurred !");
}
});// End of ajax
processorder.java (servlet)
-------------------------------
Processes data
Set some session variables
List<OrderDetails> newod = new ArrayList<OrderDetails>();
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
JsonElement orderDetailElement = null;
//update orderDetailElement
orderDetailElement = gson.toJsonTree(newod);
jsonObject.add("OrderDetails", orderDetailElement);
request.setAttribute("OrderDetails", newod); //set the session with orderdetails
out.print(jsonObject.toString()); // write object to json
checkout.java (servlet)
----------------------------
**How can I access JSON object which I am sending from processorder?**
any idea?
You need to make an ajax call inside success function of your first ajax call.
Something like
$.ajax({
url : "processorder",
type : "POST",
dataType : "text",
data : formData,
success : function(response) {
$.ajax({
url : "checkout",
type : "POST",
dataType : "text",
data : response,
success : function(response) {
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Error ");
}
});
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Oops ! Error occurred !");
}
});
I have created a REST service at "/post/search/{id}" and when I call this URL from my jquery code sometimes it gets called sometimes not. What is the exact problem in it. Is it regarding jquery or my code. My jquery code is as follows:
function functionname(clicked_id) {
$('#idForm').submit(
function(e) {
$.ajax({
type : 'POST',
url : "${pageContext.request.contextPath}/post/search/"+ clicked_id,success : function(data) {
}
});
});
}
My button code is :
<input type="submit" value="Express Intrest" id="abc" onclick=functionname(this.id) />
try like this.
function yourFunc() {
$.ajax({
type : 'POST',
url : 'yourcontroller/action',
contentType : "application/json; charset=utf-8",
dataType : 'json',
data : param,
async : false,
cache: false,
success : function(dataList) {
//alert("dataList ---> "+dataList);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest + " - " + errorThrown);
}
});
}
pass parameter values in param like this :-
var param;
param={param1:"val",param2:"val", param3:"val"};
change your button type from submit to button.
Because when you click on button your page start submitting.so the ajax function is sometime completed not completed before page.
<input type="button" value="Express Intrest" id="abc" onclick=functionname(this.id) />
The test looks like this :
#Test
public void testSave() throws Exception {
request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
request.setContentType("application/json");
// request.setMethod("post");
ActionProxy proxy = getActionProxy("/save");
actions.MyAction myAct = (actions.MyAction) proxy.getAction();
String result = proxy.execute();
System.out.println("test id : " + myAct.getId());
System.out.println("test name : " + myAct.getName());
assertEquals("success", result);
System.out.println(response.getContentAsString());
}
I'm trying to post a JSON to a struts2 action and I'm getting :
test id : null
test name : null
Although, if I try the same using a JSP :
test.jsp
<script>
var data = '{"id":"1","name":"nitin"}';
$.ajax({
url: "http://localhost:8084/Struts2Junit4/save",
data: data, //returns all cells' data
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function(res) {
console.log(res);
}
});
</script>
I get both the parameters.
I think I'm missing something in writing the test-case. Please help.
The JSONInterceptor looks for the content-type header that is why you need to use request.addHeader instead of request.setContentType.
request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
request.addHeader("Content-Type", "application/json");