Gabriel
Gabriel

Reputation: 65

Uncaught ReferenceError when calling REST Service using jQuery

I'm really new in web services, so I would appreciate any help here. I have created a RESTful web service using Spring-boot. The code for my web service is simple as I'm just testing:

@RestController
public class MainController {   
    @RequestMapping("/test")
    public String getStringTest(@RequestParam(value="name", defaultValue="Test") String name){
        System.out.println("Name received: " + name);
        return "HelloTest: " + name;
    }
}

After deploying the web service, I'm able to access it using: http://localhost:8080/imagesTest and I get the "HelloTest" string in my browser, so it's working fine. But the problem is when When I try to access it using jQuery in a web page it's not working. This is the page:

<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 </head>
 <body>
  <p id="info"></p>
 </body>
</html>
<script>
 $(document).ready(function(){

    $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        url: "http://localhost:8080/test?name=Gabriel",
        success: function(data){
            alert("Success: " + data);
        },
        error: function(){
            alert("Something went wrong.");
        }
    });

 })
</script>

When I execute my page, I get the following error message in the console:

Uncaught ReferenceError: HelloTest is not defined(anonymous function) @ imagesTest?callback=jQuery1113027941066049970686_1447350578572&_=1447350578573:1

Any help on this would be very much appreciated so I can understand what's really going on.

Thank you in advance for your help.

Upvotes: 0

Views: 1576

Answers (1)

Andreas
Andreas

Reputation: 21881

dataType: 'jsonp' tells jQuery to expect JSONP, but your returning a plain string "HelloTest: Gabriel"

Change the dataType to something more suitable, such as "text" (or remove it completely)

$.ajax({
    type: 'GET',
    dataType: 'text',
    url: "http://localhost:8080/test?name=Gabriel",
    success: function(data){
        alert("Success: " + data);
    },
    error: function(){
        alert("Something went wrong.");
    }
});

The possible values are listed in the api documentation of the $.ajax method

Upvotes: 1

Related Questions