Renzchler
Renzchler

Reputation: 341

How to fix Spring boot controller getting null data from AJAX DELETE request?

I have tried using @QueryParam, @PathVariable and @RequestParam but my controller is not getting data request from AJAX call. I have the same approach with my other methods. Only the DELETE request is not working and I am getting null value. I have referred to this Ajax delete method in spring boot but it is not working for me.

//AJAX DELETE
var id = {"id":$("#deleteUserIdInput").val()};

$("#deleteUserModal").modal("hide");

$.ajax({
    url : "http://localhost:3000/delete-user",
    datatype : "json",
    method : "DELETE",
    data : id,
    contentType : "application/json",
    error:function(data){
        console.log(data.entity);
    }
}).done(function(data) {
        console.log(data.entity)
    }
);

//Controller
//http://localhost:3000/delete-user
@RequestMapping(value="/delete-user", method = RequestMethod.DELETE)
@ResponseBody
public Integer deleteUser(@QueryParam("id") Integer id){
    return id;
}

I am testing data before passing to request and it is not null. I expect the data passed to the request to be returned, for example 1, but I am getting undefined.

Upvotes: 1

Views: 1024

Answers (2)

Not a JD
Not a JD

Reputation: 1902

It looks like you are sending the id as the body of your request. That means you'd need to have your deleteUser method receive the body as a parameter.

What I suggest you do is DELETE from a specific URL i.e. http://localhost:3000/users/{id}

The corresponding method declaration becomes:

@DeleteMapping("/users/{id}")
@ResponseBody
public Integer deleteUser(@PathVariable("id") Integer id){
    return id;
}

And your JS will need modifying (I think - I am no good at JS) to something like (again - I am not a JS guy, sorry if this is awful!):

$.ajax({
    url : "http://localhost:3000/users/" + $("#deleteUserIdInput").val(),
    datatype : "json",
    method : "DELETE",
    contentType : "application/json",
    error:function(data){
        console.log(data.entity);
    }
}).done(function(data) {
        console.log(data.entity)
    }
);

Upvotes: 1

votouch
votouch

Reputation: 1

I think , your can't get value ,may be is the servre cors。 can you config cors ?

first request can get value for delete request , actually the delete requst is cors Virtual requst , ajax comfirm your server is ok ,can ajax go ahead send agin.

you can change post requset ,and in server change post to receive you requset.

Upvotes: 0

Related Questions