I have developed a web based program using java jersey in my back end and jsp in my front end. When I make a post API call using Ajax my back end gets the following exception.
javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)
I guess it's something wrong with the data which I'm passing through the Ajax API call.
Here is my ajax API call:
var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: obj,
dataType: 'json',
success: function () {
alert("successed");
}
});
This is my back end implemented code:
#Path("testing")
public class test {
UserRepository userRepo=new UserRepository();
#Path("users")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
userRepo.createUser(a);
return a;
}
}
You should send the data as a JSON String, not a JSON Object. Avoid the JSON.parse from your code.
var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';
Alternatively, I would construct the JS Object, and apply JSON.stringify on it. This way, the code is more readable:
var data = {
userName: "John",
password: "hgvv",
img: "New York",
fname: "kjbjk",
lname: "bkbkkj",
tp: "buhb",
address: "jhbjhb",
type: "user"
};
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: JSON.stringify(data), // added JSON.stringify here
dataType: 'json',
success: function () {
alert("successed");
}
});
Related
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());
}
Hello I have been looking at other threads like mine and I can't seem to get my code working!
I need to send the JS array containing ints to a servlet this is current code:
Javascript code:
function sendReminderEmails(){
$("#sendReminderEmails").click(function(){
var people = null;
var peopleBatch1 = null;
$.ajax({
type: "POST",
url:"getAllUnregisteredPeople",
async: false,
success: function(data){
people =JSON.parse(data);
}
});
peopleBatch1 = people.splice(0,200);
$.post("sendReminderEmails", {people:peopleBatch1, mode : "insert"} , function(data){
});
});
}
Servlet Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response){
String peopleIDs[] = request.getParameterValues("people");
}
It keeps returning null! Can someone tell me if I am doing something wrong ?
You must use JSON.stringify to send your JavaScript object as JSON string.
Change your code
var obj = { people: peopleBatch1, mode: "insert" };
$.post("sendReminderEmails",JSON.stringify(obj) , function(data) {});
On Servlet side you need you use
String jsonStr = request.getParameter("people");
then Convert this jsonStr to JSON object.
in "$ajax" you need to pass the required parameter, eg
var myArray={'john', 'paul'};
$.ajax ({
type: "POST",
url:"getAllUnregisteredPeople",
data: {people: myArray}
async: false,
success: function(data) {
people = JSON.parse(data);
}
});
I have the following code that works:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassPost(#RequestBody ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and the corresponding ajax call by post:
$.ajax({
url: '/jsonasclass/',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
}),
contentType: 'application/json',
mimeType: 'application/json',
success: _callBack,
error: _errorCallback
});
Now I want to achieve the same thing, but I want to do it by GET. Anyone knows how?
I have tried changing POST to GET (in both controller and ajax call) but it did not work.
The error I get: description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Thanks to RaulRene's comment here is how you would do it.
get rid of #RequestBody from the controller and change method to get.
send the properties of the class in the controller as browser variables and spring will automatically map them to the class.
Here is the solution:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassGet(ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and corresponding ajax:
$.ajax({
url:'/jsonasclass/',
type: 'GET',
data: {
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
},
success: _callBack,
error: _errorCallback
});
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/)
Here is Client side code:
function startAjax() {
$.ajax({
type : 'GET',
url : 'customers/ShowAllCustomers',//this is url mapping for controller
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
success : function(response) {
alert(response.get(0).first_name);
//this response is list of object commming from server
},
error : function() {
alert("opps error occured");
}
});
}
and here is my Controller:
#RequestMapping(value="/ShowAllCustomers", method = RequestMethod.GET)
public #ResponseBody List<Customer> AllCustomersList() {
List<Customer> customers= customerService.getAllCustomers();
return customers;
}
Everytime "oops error occured" alert appears. Can you please point out error in this for me. I will be really thankful......
List<Customer> customers= customerService.getAllCustomers();
return customers;
The above code returns a Java List , but the jQuery is expecting a JSON String .
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
You need to convert the List to a JSON string using some JSON library.