robert trudel
robert trudel

Reputation: 5749

Jquery Ajax call return an error but work with curl

I do a ajax call with jquery

<form class="navbar-form" role="search">
     <div class="input-group">
         <input type="text" class="form-control" placeholder="Rechercher" name="srch-term" id="srch-term">
         <div class="input-group-btn">
             <button id="lodgerSearch" type="button" class="btn btn-default"><i class="glyphicon glyphicon-search"></i></button>
         </div>
     </div>
</form>

$('#lodgerSearch').on('click', function (e) {
  var searchParam = $('#srch-term').val();
  var url = "http://localhost:8080/lodgers/search";

  if(searchParam!=""){
    url = "http://localhost:8080/lodgers/search?searchTemp=" + searchParam; 
  }

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function (data, status, jqXHR) {
        alert(data);
        // do something
        alert("sucess");
    },
    error: function (jqXHR, status) {
        // error handler
        alert("error " + jqXHR + " -  " + status);
    }
  });
});

with the ajax call in the browser I get this message

error [object Object] -  error

my controller in java

@RequestMapping(value = "/lodgers/search", method = RequestMethod.GET)
public List<LodgerSearch> getAllLogders(@RequestParam(value = "inactiveLodger", required = false) boolean inactiveLodger, @RequestParam(value = "searchTerm", defaultValue="") String searchTerm) {
    return lodgerService.searchLodger(inactiveLodger, searchTerm);
}

If i do curl localhost:8080/lodgers/search I get the expected result

[{"lodgerId":1,"firstName":"Marc","lastName":"Collin","birthdate":"2015-06-17","nas":null,"nam":null,"buildingRoom":null},{"lodgerId":2,"firstName":"yvan","lastName":"Dubois","birthdate":"2015-06-18","nas":null,"nam":null,"buildingRoom":null}]

Upvotes: 1

Views: 235

Answers (1)

Nelson Teixeira
Nelson Teixeira

Reputation: 6562

The problem is in parameters concatenation.

This code:

if(searchParam!=""){
  url = "http://localhost:8080/lodgers/searchTemp?" + searchParam; 
}

doesn't call http://localhost:8080/lodgers/search, it calls http://localhost:8080/lodgers/searchTemp (not a parameter).

when you use curl, you passing the right url so it returns ok.

Change the above code to

if(searchParam!=""){
  url = "http://localhost:8080/lodgers/search?searchTemp=" + searchParam; 
}

include the other parameter as well if you like.

Upvotes: 1

Related Questions