3

In a web page, I want to provide some buttons to do some actions, for example, delete user. I don't want to create one form for each button, so I thought an ajax post request would be the best way to accomplish this. For some reason the URL is not intercepted by the controller, only if I add the project's name then it would work (e.g. url : "projectname/users/remove"). I obviously don't want to hard code the project name on every ajax request nor have a project name variable. What would be the right way to make such a request by only specifying "/users/remove" for the url/action?

function removeUser(userid){    
    var r = confirm("Are you sure you want to delete user '" + userid + "''?");

    if (r == true) {
        $.ajax({
            type : "POST",
            url : "/users/remove",
            data : {
               userid: userid
            },
            success : function(response) {
               alert("Suceeded!");
            },
            error : function(e) {
               alert('Failed!: ' + e);
            }
        }); 
    }
}

Thanks in advance Diego

DiegoSahagun
  • 730
  • 1
  • 11
  • 22

1 Answers1

3

If you are on an exact page url for example: webpage.com, and you want to send request to webpage.com/users/remove.

Remove the leading "/" like this:

url : "users/remove"

You should send the request like this, in this way it's only adds to the current url, the first "/" means you want to go to the root, which is different in for example in eclipse and IntelliJ.

If you want the advanced solution, you should make a variable with jsp and c:url.

Fadamaka
  • 71
  • 4
  • Thanks for your comment. I definitely don't want to constraint my web applicatio to work only on root. As for the variable, that could be a solution but if the context is aware of the web application's name (deployment url) why should I bother on adding it? So far it works fine with forms when I do something like: `
    `
    – DiegoSahagun Aug 31 '15 at 09:42
  • You misunderstood me, this solution worked for me: http://stackoverflow.com/questions/7681202/how-to-perform-equivalent-of-jsps-curl-in-javascript – Fadamaka Aug 31 '15 at 11:48
  • I meant this: leave the first "/" out and it wont go to root. – Fadamaka Aug 31 '15 at 11:50
  • Thanks! Removing the leading "/" indeed worked. It is strange, Thymeleaf's documentation says: "Context-relative URLs start with /". [source](http://www.thymeleaf.org/doc/articles/standardurlsyntax.html). Well, I am glad the controller is being called. – DiegoSahagun Sep 01 '15 at 11:17