Reading json with javascript from jsp file - java

So I have a JSP file where I simply output the json code, and I'm trying to use that json in my javascript script (in another page), but it doesn't seem to work, the console says that that the returned value is undefined. If I give some "real" API URL, it works though.
This is my json_company.jsp
<%#page import="algo.user36.Service"%>
<%# page contentType="application/json" pageEncoding="ISO-8859-1"%>
<%
Service service = new Service();
out.print(service.generatedJsonCompany());
%>
This is my javascript function
function getData() {
$.getJSON( "json_company.jsp", function( data ) {
console.log(data);
});
}
If I go directly to json_company.jsp, it is the excepted output.
Is this a way that isn't supposed to work?

Accordingly to the code that you have provided.
callback([ {"product_description":"Blueberries 1kg","QTE":"54797.0","REVENUS":"357873.6"}, {"product_description":"Mixed Fruits 500g","QTE":"153549.0","REVENUS":"690961.5"}, {"product_description":"Nuts 500g","QTE":"184481.0","REVENUS":"872008.44"}, {"product_description":"Original 1kg","QTE":"51175.0","REVENUS":"300284.4"}, {"product_description":"Raisins 1kg","QTE":"145205.0","REVENUS":"670625.85"}, {"product_description":"Strawberries 500g","QTE":"68685.0","REVENUS":"363077.0"}]);
You return callback function, not json itself that is typical for jsonp request. Try to predefine callback function in your javascript before call.
function callback(data){
console.log(data);
}
Give it a try:
$.ajax({
type: 'GET',
url: "json_company.jsp",
async: false,
jsonpCallback: 'callback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
And be sure to check your request in firebug\chrome console to exclude 404 code.

Related

Spring Ajax JQuery Jackson

Whats wrong in my approach.
Java Mapping :
#POST
#Path("/receive")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void consumeJSONList(#RequestBody List<Question> clientList) {
String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";
System.out.println(output);
}`
Ajax Call :
function addData(x) {
var x='[{"id":12,"email": "2","lang": "es"}]';
$.ajax({
type: 'POST',
url: "rest/question/receive",
header : {
"Content-Type":"application/json"
},
data: x,
success: function(data, textStatus, jqXHR){
alert('Wine created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
alert(jqXHR+'addWine error: ' + textStatus+"errorThrown"+errorThrown);
}
});
}
i am able hit the same url with same data in google post man but when use ajax call its throwing 415(Unsupported media type)
Please help to create a controller which can accept list of java object and process the same
As the jQuery docs say, you should give the following a try:
Replace…
header : {
"Content-Type":"application/json"
},
…with…
dataType: 'json',
…and make sure that the server's context path in front of "/receive" is really "rest/question". Depending on the situation also a leading slash "/rest/question/receive" could be worth a try.

How to redirect to different JSP page with the JSON result from spring rest controller and display those values in that jsp page

function submitForm() {
var id = $("#id").val();
var name = $("#name").val();
$.ajax({
type : "POST",
contentType: "application/json",
data : JSON.stringify({
"id":id,
"name":name,
}),
dataType: "json",
url : "rest/emp/create",
success : function(data) {
//alert("created Employee"+data.name+data.id);
}
});
}
i want to redirect to another jsp page with json response from spring controller.
in the above java script function i am calling a spring controller to create an employee data. after successful creation i need to redirect to some other jsp page with the created return value from the spring controller which is json value.
Finally i found the answer to this question. But please confirm whether it is right.
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(emp.getId()).toUri());

Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) in Java RESTful web service call

I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function).
Here is the ajax query from my test html page:
$(function(){
$('.message-button').on('click', function(e){
var resultDiv = $("#resultDivContainer");
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'http://localhost:8080/xxxAPI/api/activity',
'data': { "baseItemId": "2" },
'dataType':'json',
'success': function(data) {
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
$("#resultDivContainer").text(xmlstr);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert(' Error in processing! '+textStatus + 'error: ' + errorThrown);
}
});
})
});
Also here is the part of my java code that accepts post requests:
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(XxxxxActivity entity) {
super.create(entity);
}
When I request from the test page (for this version of the test page), I get this error:
Failed to load resource: the server responded with a status of 415
(Unsupported Media Type)
or this error:
POST http://localhost:8080/xxxAPI/api/activity 415 (Unsupported
Media Type)
So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to jsonp, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked.
Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF.
I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.
PS: Also note that GET requests from the browser work fine. I have not used maven in this project.
Replace
'data': { "baseItemId": "2" },
with
'data': JSON.stringify({ "baseItemId": "2" }),
Object JSON is available here.
EDIT
add attribute contentType: 'application/json; charset=UTF-8'
remove attribute headers from ajax call.
Frondend
$.ajax({
contentType: "application/json; charset=utf-8",
url: '/GetList',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ 'Name': 'mehmet erdoğdu'}),
beforeSend: function () {
}, success: function (data) {
}, complete: function () {
}, error: function (data) {
}
});
Backend
[HttpPost]
public JsonResult GetList([FromBody] NameRequest req)
{
var selectListItems = new List<SelectListItem>
{
new SelectListItem
{
Value = "",
Text = "Select Name"
}
};
//
return Json(selectListItems, new JsonSerializerSettings());
}

Java Rest call with jquery and ajax

I am making a ajax Rest call within jquery and it is supposed to return me a list of beans, which I want to show in the jsp. I am able to make the Rest call but I can't get how to get the result in the ajax call and show it in page.
jsp page with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$('#abcForm').submit(function(){
var v = $('#abc').val();
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
});
});
});
</script>
java code
#Path("hello")
public class RestController {
#GET
#Path("{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Hello : " + msg;
return Response.status(200).entity(output).build();
}
}
So actually there will be a rest call from the java class and it will return a list which needs to be shown in the jsp page as ajax call. This is where I am stuck.
Help needed.
Thanks
You have a success callback that will be called when the request finishes as successful and will receive the response as the first parameter:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
success: function(data) {
//do something with data.
}
});

Spring MVC: Receive XML data and Send String message back

I am trying to collect all the form data and send it as a XML to Controller. This XML will further be sent to back end which will take care of it.
There is no need to marshal this XML into an Object.After receiving this XML I just need to send a String success message back.
It is half working. I am able to receive XML message from UI page and able to print it on console. But when I just send success message back UI ajax call receives No conversion from text to application/xml
#RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml","text/plain"})
#ResponseBody public String handleSave(#RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);
return "Success";
}
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
processData: false,
data: collectFormData1(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown::'+errorThrown);
}
});
return false;
});
Try to remove dataType: 'application/xml' from jquery code.
As mentioned in documentation: DataType: The type of data that you're expecting back from the server.
(http://api.jquery.com/jQuery.ajax/)

Categories