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.
Related
I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)
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) />
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();
i have a problem with passing values to the controller(jave) from javascript file after serialising the entries. when i run in debug mode its passing values to the controller but if its run straight away then its not passed. i first serilzed the values entered in the form and then post to the controller. any ideas please... the code is as follows function
submitSearch() {
var searchParams = $("#search-filters, #keyword-desktop-filters, #keyword-mobile-filters").serialize();
alert(searchParams);
$.ajax({
url: 'search?' + searchParams,
type: 'POST',
success: function (msg) {
alert("hai");
},
error: function (xhr) {
alert("kooyi");
}
});
}
Try to pass your search parameters like data parameter in your .ajax function settings object. Here the example:
$.ajax({
url: 'search' ,
type: 'POST',
data: $("#search-filters, #keyword-desktop-filters, #keyword-mobile-filters").serialize(),
success: function (msg) {
alert("hai");
},
error: function (xhr) {
alert("kooyi");
}
});
And here is .ajax method' API: http://api.jquery.com/jQuery.ajax/