display results in jsp by calling a servlet using jquery ajax? - java

I want to call a servlet. servlet will fetch the data from database and keeps it in request. And the result i need t display in some.jsp using jstl tags.
$('#ownForm #myButton').click(function() {
$.ajax({
type: "GET",
url: "./controller",
success: function(msg) {
//Todo
},
error: function(ob,errStr) {
//Todo
}
});
});
In servlet i have below code:
//keep database returned list in request
request.setAttribute("myresult", result);
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
Please help me how can i achieve it?

Ignore the jsp. Use FlexJson to serialize your result directly from the result object to json. Print the serialized result to the out stream in the response.
Something like this:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
JSONSerializer serializer = new JSONSerializer();
serializer.exclude("*.class"); //reduce clutter in your output as you see fit
serializer.serialize(objectToSerialize, response.getWriter());
Using jquery, parse this json and act on the result.

Related

What should a servlet return that only is receiving data?

I implemented a servlet that receives a JSON string, converts it into an object and inserts its data into the database. I call that servlet from a HTML page using AJAX and post the JSON string to it. In my case, does it make sense for the servlet to write anything to the response?
Since you mention that you had an ajax call to your servlet, you should probably return a JSON status back to calling .ajax()
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your database operation insert is successful
JSONObject json = new JSONObject();
// put a success message into the JSON object .
json.put("status", "success");
out.print(jsonObject);
out.flush();
On the client side
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
}
You need not to return anything. Once the request cycle complete, your browser receives the response object of it as a stream. If you want to add something to it.
response.getWriter().write(somedata);
That somedata you'll receive in your AJAX callback.
For detailed example with codes : How to use Servlets and Ajax?
It is good practice to perform the database transaction inside a try catch block, and return a success / failure status flag to the client, in case the transaction failed for whatever reason.

How to display data of MYSQL in java with using of AJAX

I have one table in mysql which has three field with data inserted. there are three fields in it which are as below.
i want to display this data on a web browser with using ajax in java.
i search on a net and find this below code are most useful
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ajax_demo","root","");
PreparedStatement ps=con.prepareStatement("select * from ajax");
what are other things i have to implement for displaying output.
You need to do a AJAX request, the main code body for an ajax request is the following
request.onreadystatechange=handleResponse;
request.open(typeReq, url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.send(queryString);
typeReq is the type of the request: POST or GET.
url: the destination url address.
queryString: the set of data which you want to send.
handleResponse is a function to hanled the response. For example:
function handleResponse () {
if (request.readyState = 4) {
if (request.status = 200) {
var response = request.responseText;
//code to handle response
} else {
//code to handle errors
}
}
Now, you can use an API like prototype or jquery, it's easier.
I hope this information helps you.
Good Luck

How to get JSON data from POST request using Servlet

This is my code on the client side:
$.ajax({
type:'POST',
charset:'utf-8',
url:'http://localhost:8180/GisProject/MainService',
data:JSON.stringify(params),
success:function(msg)
{
console.log(msg);
},
error:function(xhr,status)
{
console.log(status);
},
contentType:"application/json"
});
I have previously parsed this data in Node using express.bodyParser but now I have to parse it using the servlet.I have seen people assign variables here without using JSON.stringify and getting that variable using request.getParameter(myData).
What is the standard way of getting the JSON data into the servlet?
And why do people seem to be sending Javascript objects with JSON embedded as a String within like data:{mydata:JSON.stringify(actualData)}?
In case I was not being clear,I want to use the doPost method's request object to get the data I sent from the client side.
On the server side in a servlet you can read POST data payload from request.getReader()
And you can use JSON library like GSON to parse JSON. Something like:
YourClass obj = new Gson().fromJson(request.getReader(), YourClass.class)
Try this:
$.ajax({
type:"POST",
url:'http://localhost:8180/GisProject/MainService',
data:{mydata:JSON.stringify(params)},
datatype:"json",
success:function(msg)
{
console.log(msg);
},
error:function(xhr,status)
{
console.log(status);
},
});
you can send request and response object to doGet method and than get the json in the same way.
Way to send object to doGet
doGet(request, response); call it in to the post method.
Hope this should help for you:
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

How to send an array from Servlet to Java Script with AJAX?

I need send an array to js with ajax, this is my function with ajax in a java script...
$.ajax({
url: "/localizacion/ServletPeticiones",
type:"Post",
data:"accion=LatLong_UR",
dataType: "text",
success: function(results){
console.info(results);
cad=results;
}
});
I've got an array String[][] datos, and I have to send this array from my Servlet to JS with the last function.
How I can do this?
How receive the array from my Servlet with my function of ajax in a js?
The servlet will return a application/json response, and a JSON-encoded array (better, you can use a Map<String, String>). There are libraries, like Gson, to do the conversion:
public void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json; charset=UTF-8");
Gson gson = new Gson();
Map<String, String> datos = getDatos(); // you have to implement this
response.getWriter().println(gson.toJson(datos));
}
You can try using JSON .. you can use google's GSON library to convert an array into JSON representation and send it to your client
On the client side ... change the $.ajax's dataType to "json"
In the success function you just use the returned data as javascript array
JSON would be the right way to go about it. PHP has json_encode function that very well does it for you from arrays. Another way is to manually create a JSON string although it's not a good idea. On the other hand, just for practice and get familiar with JSON, it's advisable, but you are better of using built-in json generating capabilities of your server side platform.
You might want to send a correct header from the server so browsers are able to receive it as json data: "Content-Type: application/json"

I'm unable to receive the json object sent from my servlet

$(document).ready(function() {
var path = null;
console.log('${pageContext.request.contextPath}/loadfile');
$.ajax({
dataType: "json",
url: '${pageContext.request.contextPath}/loadfile',
success: function(data){
$.each(data,function(index,obj){
console.log(obj.id);
alert('inside');
path = obj.path;
});
}
});
here /loadfile is the url which returns the json object , when I go to this url I am able to see the JSON object printed on the html page , however I dont get the same when I access the page which contains the above javascript code
Often people don't tell their server to the the browser that the JSON string they are sending is to be interpreted as a json object.
Despite the fact that dataType:'json' is supposed to sort it out, it is not always the case.
in PHP
header("Content-type: application/json");
ASP
Response.AddHeader('Content-Type', 'application/json');
Failing that,
success: function(data){
if (typeof data!='object') data=$.parseJSON(data); // make sure it's an object
I can't figure out why jQuery doesn't fix it but the response headers, even with dataType:'json' set can appear as application/x-www-form-urlencoded; charset=UTF-8 and the object doesn't get created.

Categories