I am working with springmvc and angularjs. I'm trying to send the String response from springmvc controller to the angular controller, but facing the below error message shown on the browser console and the response which returned from springmvc is not getting printed in the angularjs side.
ERROR:
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Sample code:
js:
myApp.controller('myTestCtrl', function ($rootScope, $scope,MyService) {
$sco[e.submitInfo = function(){
var data = new FormData();
var allInfo =
{
'name': $scope.name,
'id': $scope.id,
'product': $scope.product,
'message':$scope.message
}
//files to be attached if exists
for (var i in $scope.filesAttached) {
var file = $scope.filesToAttach[i]._file;
data.append("file", file);
}
MyService.sendAllInfo(data).then(
function (response) {
if (response === "") {
alert("success");
//logic
}else{
alert("in else part " + response);
}},
function (errResponse) {
console.log("Error while retrieving response " + errResponse);
});
};
});
}});
MyService:
myService.sendAllInfo = function (data) {
var deferred = $q.defer();
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: []
}
$http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
deferred.reject(errResponse);
}
);
return deferred.promise;
};
Spring mvc:
#RequestMapping(value = "/allInfo", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public #ResponseBody
String allInfoData(#RequestParam("data") String data,#RequestParam("file") List<MultipartFile> files){
//logic
return "success";
}
In my above spring controller code, i'm returning success string to angularjs controller, but in the browser the below error is displayed.
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Note: Above is only the sample code , it is perfectly hitting the spring controller and issue is only while catching the response from spring controller to angular controller.
I tried to change produces=MediaType.TEXT_PLAIN_VALUE to produces={"application/json"} but still it is showing the same error.
To avoid parsing the string, use transformResponse: angular.identity:
myService.sendAllInfo = function (data) {
̶ ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: [],
//IMPORTANT
transformResponse: angular.identity
}
var promise = $http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
return response.data;
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
throw errResponse;
}
);
return promise;
};
Also avoid using the deferred Anti-Pattern.
In the response there are some values which are simple text not String so You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
The best solution is use responseType: "text" as "json" it will woke
I'm trying to develop a small application to create index on local elasticsearch engine. I use angularjs on the front-end, and spring-boot on the back-end. It can create index successfully, however, when I want to retrive the response in the front-end, it keeps throwing me errors.
Below is my AngularJS api call:
app.service('ESIndexService', function($http) {
this.createESIndex = function(esindexObj) {
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj
};
return $http(settings).then(function(response) {
console.log("response:"+response);
return response;
}, function(error) {
console.log("error:"+error);
return error;
});
};
});
Then this is my controller:
#CrossOrigin
#RestController
#RequestMapping(value = "ESIndex")
public class ESIndexController {
#RequestMapping(value = "createESIndex", method = RequestMethod.POST)
public #ResponseBody String createIndex(#RequestBody ESIndex esIndex) {
try {
Settings settings = Settings.builder()
.put("xpack.security.user", String.format("%s:%s", Constants.ES_UNAME, Constants.ES_PWD)).build();
TransportClient client = new PreBuiltXPackTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Constants.ES_HOST), Constants.ES_PORT));
CreateIndexResponse response = client.admin().indices().prepareCreate(esIndex.getName()).setSettings(Settings.builder()
.put("index.number_of_shards", esIndex.getNumberOfShards())
.put("index.number_of_replicas", esIndex.getNumberOfReplicas())).get();
client.close();
if(response.isAcknowledged() && response.isShardsAcked())
return Constants.SUCCESS;
else
return "Fail to create index!";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
I want to get the response status and data in AngularJS response. However, it keeps throwing me errors:
error:SyntaxError: Unexpected token i in JSON at position 0
I'm not using JSON.parse function, why it gives me error like this?
After adding responseType: 'text', still throwing same error, the chrome nextwork
It turns out I need to add "transformResponse: undefined", however, in another of my project, I never did this. What's the difference?
AngularJS:
this.newBlog = function(blogObj) {
var settings = {
method: 'POST',
url: baseUrl + "/blog/newBlog.do",
data: blogObj
}
return $http(settings).then(function(response) {
return response;
}, function(error) {
return error;
});
};
Java Controller:
#RequestMapping(value="newBlog.do", method=RequestMethod.POST)
public #ResponseBody String newBlog(#RequestBody Blog blog, HttpServletRequest request) {
User createdBy = (User) request.getSession().getAttribute("user");
if(createdBy == null)
return NO_SESSION_MSG;
else {
createdBy.setPwd(null);
blog.setCreatedAt(TQBUtilities.getCurrentTime());
blog.setLastUpdatedAt(TQBUtilities.getCurrentTime());
blog.setCreatedBy(createdBy);
return blogService.newBlog(blog);
}
}
Angular is automatically trying to parse the server response as JSON. Try adding this to your settings object
responseType: 'text'
So
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
responseType: 'text'
};
#jheimbouch add "transformResponse: undefined" to http call, like below, works fine:
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
transformResponse: undefined
};
However, why it is required in angularjs 1.6.2? When I was using AngularJS 1.4.8, I don't need to add transformResponse attributes.
Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");, I want to catch this message ('user name already exists') in the jQuery AJAX error message.
jQuery("#save").click(function () {
if (jQuery('#form').jVal()) {
jQuery.ajax({
type: "POST",
url: "saveuser.do",
dataType: "html",
data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
jQuery("#usergrid").trigger("reloadGrid");
clear();
alert("Details saved successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
On the second alert in the error callback, where I alert thrownError, I am getting undefined and the xhr.status code is 500.
I am not sure where I am going wrong. What can I do to fix this problem?
Make sure you're setting Response.StatusCode to something other than 200. Write your exception's message using Response.Write, then use...
xhr.responseText
..in your javascript.
Controller:
public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
response.Write(filterContext.Exception.Message);
response.ContentType = MediaTypeNames.Text.Plain;
filterContext.ExceptionHandled = true;
}
}
[ClientErrorHandler]
public class SomeController : Controller
{
[HttpPost]
public ActionResult SomeAction()
{
throw new Exception("Error message");
}
}
View script:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
ServerSide:
doPost(HttpServletRequest request, HttpServletResponse response){
try{ //logic
}catch(ApplicationException exception){
response.setStatus(400);
response.getWriter().write(exception.getMessage());
//just added semicolon to end of line
}
}
ClientSide:
jQuery.ajax({// just showing error property
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
}
}
});
Generic Ajax Error Handling
If I need to do some generic error handling for all the ajax requests. I will set the ajaxError handler and display the error on a div named errorcontainer on the top of html content.
$("div#errorcontainer")
.ajaxError(
function(e, x, settings, exception) {
var message;
var statusErrorMap = {
'400' : "Server understood the request, but request content was invalid.",
'401' : "Unauthorized access.",
'403' : "Forbidden resource can't be accessed.",
'500' : "Internal server error.",
'503' : "Service unavailable."
};
if (x.status) {
message =statusErrorMap[x.status];
if(!message){
message="Unknown Error \n.";
}
}else if(exception=='parsererror'){
message="Error.\nParsing JSON Request failed.";
}else if(exception=='timeout'){
message="Request Time out.";
}else if(exception=='abort'){
message="Request was aborted by the server";
}else {
message="Unknown Error \n.";
}
$(this).css("display","inline");
$(this).html(message);
});
You need to convert the responseText to JSON. Using JQuery:
jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);
If making a call to asp.net, this will return the error message title:
I didn't write all of formatErrorMessage myself but i find it very useful.
function formatErrorMessage(jqXHR, exception) {
if (jqXHR.status === 0) {
return ('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status == 404) {
return ('The requested page not found. [404]');
} else if (jqXHR.status == 500) {
return ('Internal Server Error [500].');
} else if (exception === 'parsererror') {
return ('Requested JSON parse failed.');
} else if (exception === 'timeout') {
return ('Time out error.');
} else if (exception === 'abort') {
return ('Ajax request aborted.');
} else {
return ('Uncaught Error.\n' + jqXHR.responseText);
}
}
var jqxhr = $.post(addresshere, function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) {
var responseTitle= $(xhr.responseText).filter('title').get(0);
alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) );
})
If someone is here as in 2016 for the answer, use .fail() for error handling as .error() is deprecated as of jQuery 3.0
$.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
//handle error here
})
I hope it helps
This is what I did and it works so far in a MVC 5 application.
Controller's return type is ContentResult.
public ContentResult DoSomething()
{
if(somethingIsTrue)
{
Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
Response.Write("My Message");
return new ContentResult();
}
//Do something in here//
string json = "whatever json goes here";
return new ContentResult{Content = json, ContentType = "application/json"};
}
And on client side this is what ajax function looks like
$.ajax({
type: "POST",
url: URL,
data: DATA,
dataType: "json",
success: function (json) {
//Do something with the returned json object.
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
xhr.status;
//The message added to Response object in Controller can be retrieved as following.
xhr.responseText;
}
});
A general/reusable solution
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
Custom exception ModelStateException that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)
Custom controller action error filter HandleModelStateExceptionAttribute that catches custom exception and returns HTTP error status with model state error in the body
This provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success and error handlers.
Client side code
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
Server side code
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog post where you can find all the code to run this in your application.
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
in code error ajax request for catch error connect between client to server
if you want show error message of your application send in success scope
such as
success: function(data){
// data is object send form server
// property of data
// status type boolean
// msg type string
// result type string
if(data.status){ // true not error
$('#api_text').val(data.result);
}
else
{
$('#error_text').val(data.msg);
}
}
I found this to be nice because I could parse out the message I was sending from the server and display a friendly message to the user without the stacktrace...
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
This function basically generates unique random API key's and in case if it doesn't then pop-up dialog box with error message appears
In View Page:
<div class="form-group required">
<label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
<div class="col-sm-6">
<input type="text" class="apivalue" id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />
<button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
</div>
</div>
<script>
$(document).ready(function(){
$('.changeKey1').click(function(){
debugger;
$.ajax({
url :"index.php?route=account/apiaccess/regenerate",
type :'POST',
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function(data){
var result = data.sync_id.toUpperCase();
if(result){
$('#api_text').val(result);
}
debugger;
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
});
</script>
From Controller:
public function regenerate(){
$json = array();
$api_key = substr(md5(rand(0,100).microtime()), 0, 12);
$json['sync_id'] = $api_key;
$json['message'] = 'Successfully API Generated';
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails.
The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
This is probably caused by the JSON field names not having quotation marks.
Change the JSON structure from:
{welcome:"Welcome"}
to:
{"welcome":"Welcome"}
You have a JSON object of the exception thrown, in the xhr object. Just use
alert(xhr.responseJSON.Message);
The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'
I believe the Ajax response handler uses the HTTP status code to check if there was an error.
So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.
I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.
I then set the Response.StatusCode to either 500 or 200 whether I had an error or not.
jQuery.parseJSON is useful for success and error.
$.ajax({
url: "controller/action",
type: 'POST',
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(jqXHR.responseText);
notify(data.toString());
notify(textStatus.toString());
},
error: function (data, textStatus, jqXHR) { notify(textStatus); }
});
$("#save").click(function(){
$("#save").ajaxError(function(event,xhr,settings,error){
$(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
});
});
Throw a new exception on server using:
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
I believe that the StatusDescription is returned to the Ajax call...
Example:
Try
Dim file As String = Request.QueryString("file")
If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")
Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()
sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)
file = IO.Path.Combine(sTmpFolder, file)
If IO.File.Exists(file) Then
IO.File.Delete(file)
End If
Catch ex As Exception
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
End Try
Although it has been many years since this question is asked, I still don't find xhr.responseText as the answer I was looking for. It returned me string in the following format:
"{"error":true,"message":"The user name or password is incorrect"}"
which I definitely don't want to show to the users. What I was looking for is something like below:
alert(xhr.responseJSON.message);
xhr.responseJSON.message gives me the exact message from the Json Object which can be shown to the users.
$("#fmlogin").submit(function(){
$("#fmlogin").ajaxError(function(event,xhr,settings,error){
$("#loading").fadeOut('fast');
$("#showdata").fadeIn('slow');
$("#showdata").html('Error please, try again later or reload the Page. Reason: ' + xhr.status);
setTimeout(function() {$("#showdata").fadeOut({"opacity":"0"})} , 5500 + 1000); // delays 1 sec after the previous one
});
});
If there is any form is submit with validate
simply use the rest of the code
$("#fmlogin").validate({...
...
...
});
First we need to set <serviceDebug includeExceptionDetailInFaults="True" /> in web.config:
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
**<serviceDebug includeExceptionDetailInFaults="true" />**
</behavior>
</serviceBehaviors>
In addition to that at jquery level in error part you need to parse error response that contains exception like:
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
Then using r.Message you can actully show exception text.
Check complete code: http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html
In my case, I just removed HTTP VERB from controller.
**//[HttpPost]** ---- just removed this verb
public JsonResult CascadeDpGetProduct(long categoryId)
{
List<ProductModel> list = new List<ProductModel>();
list = dp.DpProductBasedOnCategoryandQty(categoryId);
return Json(new SelectList(list, "Value", "Text", JsonRequestBehavior.AllowGet));
}
I am using Jquerys Ajax method to talk to my web service. The code seems OK, but I just monitored HTTP traffic using HTTPFox firefox plugin and I noticed unexpected results. To begin with, I am setting the ContentType as application/json and my web service is also producing JSON data but HTTPFox indicates Content Type for my HTTP requests as application/vnd.sun.wadl+xml (NS_ERROR_DOM_BAD_URI).
The Request Method is GET as set in my Ajax request, but HTTPFox indicates my Request method as OPTIONS. And while the Request succeeds and data is returned, the onSuccess method of my Ajax request is not called. Instead, the onError method is called. HTTP Fox is able to capture the data from my web service as response. See the image for HTTP Fox.
Finally, all other request from other processes in my browser seem OK but my HTTP requests are flagged 'RED' by HTTP Fox. The request from other pages and processes seem OK.( GREEN or WHITE).
I have attached screenshot of HTTPFox highlighted on one of my Request. The flagged ones are also from my application.
Image:
I have also pasted the Ajax code I am using to make the HTTP Requests.
window.onload = function() {
var seq_no = getParameterByName("seq_no");
var mileage = getParameterByName("mileage");
document.getElementById("seq_no").value = seq_no;
document.getElementById("mileage").value = mileage;
var param = 'vehReg='+encodeURIComponent(document.getElementById('vehReg').value);
// alert(param);
loadVehicleInfo(param);
};
function loadVehicleInfo(params) {
$("#message").html('<p><font color="green">Loading...</font></p>');
$.ajax({
type: "GET",
url: "http://localhost:8080/stockcloud/rest/vehicles/info",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function(data,status) {
$("#message").empty();
$("#message").html('<p>'+getAsUriParameters(data)+'</p>');
},
error :
function(XMLHttpRequest, textStatus, errorThrown) {
$("#message").html("<p> <font color='red'>The following error occurred: " +textStatus+ ': '+errorThrown+ "</font>");
}
});
};
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Server side Code for the request:
#Path("/vehicles")
public class VehiclesService {
#GET
#Path("info")
#Produces("application/json")
public Response getVehicleInfo(#DefaultValue("__DEFAULT__") #QueryParam("vehReg") String vehReg) {
// Send SOAP Message to SOAP Server
ServerResponse resp = new ServerResponse();
if("__DEFAULT__".equals(vehReg)) {
resp.setError("Vehicle registration must be supplied as a query parameter: ?vehReg=<THE REG NO>");
resp.setResult(false);
Response.status(Response.Status.BAD_REQUEST).entity(resp).build();
}
try {
// actual code to return the car info and return XML string with the info.
connection.disconnect();
String xml = URLDecoder.decode(s.toString(),"UTF-8");
xml = xml.replace("<", "<").replace(">", ">").replace("<?xml version='1.0' standalone='yes' ?>", "");
System.out.println(xml);
resp.setVehicle(new VehicleParse().parse(xml));
resp.setResult(true);
} catch(Exception e) {
resp.setResult(false);
resp.setError(e.getMessage());
e.printStackTrace();
Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(resp).build();
}
return Response.status(Response.Status.OK).entity(resp).build();
}
}
Is there something I am not doing right?
Thanks.
I am trying to access RESTful service, created on Java and deployed with help of Jersey using jQuery.
If I access it using browser I will get the result, but from jQuery, I am getting an error and can not see any results on the page.
Page with the script is hosting on local Apache server and the Service is running separately using Jersey/Grizzly on the same machine.
I can see that service is sending the response and it has 200 code, but I keep getting error from .ajax, without any details and
Any suggestions what is wrong?
Service:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces
public String test(){
System.out.println("Sending response");
return "test";
}
}
Main:
public static void main(String[] args) throws IOException {
final String baseUri = "http://localhost:9998/";
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages",
"resources");
System.out.println("Starting grizly");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format(
"Jersey app started with WADL available at %sapplication.wadl\n"
+ "Try out %shelloworld\nHit enter to stop it...", baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
}
JavaScript:
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
DataType: "text",
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
After a couple of days of research and experiments I discovered that the problem was in the headers of the response. To be able to use the response from the service, I added custom header field:
"Access-Control-Allow-Origin: *"
New service looks like this:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces
public Response test(){
return Response.ok("test").header("Access-Control-Allow-Origin", "*").build();
}
}
you have to set crossDomain to true to make cross domain requests
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
dataType:'html',
type:'GET',
crossDomain:true,
cache:false,
async:false,
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
UPDATE
if your service required the authentication may be you can do it like this
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
dataType:'html',
type:'GET',
crossDomain:true,
cache:false,
async:false,
xhrFields: {
withCredentials: true
},
username:'yourUsername', //not sure about the username and password options but you can try with or without them
password:'thePass',
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
also use jquery 1.5.1 or higher because the crossDomain and some other options are not available in the earlier versions. For reference see this link http://api.jquery.com/jQuery.ajax/
if you are using a javascript function to replace a typical form submission then pay attention to the fact that you should return false; at the end of your javascript function!
you can check a similar issue here http://forum.jquery.com/topic/jquery-newbie-3-9-2011
actually it is nota a matter of jersey but a matter of javascript