Marcin46
Marcin46

Reputation: 120

jQuery ajax request not to correct url

I'm trying to send ajax request via jquery. Everything it's ok except url. It should be http://localhost:8080/register but is http://localhost:8080/login so it's a url of current page. Also when I'm debugging application I can see that this request goes to controller method with "/login" value. I don't know why. It's a code of ajax method:

$("#my-signin2").on("click", function(){
    $.ajax({
        url: 'http://localhost:8080/register',
        type: 'post',
        success: function (data) {
            console.info(data);
        }
    });
});

And there are controller methods:

@RequestMapping(value = "/login")
public String login(){
    return Links.LOGIN.getUrl();
}

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(){
    return Links.HOME.getUrl();
}

Also I'm using spring security and it's code of handling csrf token:

var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken  = $("meta[name='_csrf']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(csrfHeader, csrfToken);
});

I'm getting correct answer from serwer, but from login method.

UPDATE:

Spring security was redirecting all unauthorized requests to login page, so request is ok. Thanks for help!

Upvotes: 1

Views: 1065

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You should prevent the default action first using e.preventDefault() then you could send the custom ajax request , like :

$("#my-signin2").on("click", function(e){
    e.preventDefault(); //Prevent the page from refreshing

    ....
});

Upvotes: 3

Mustapha Larhrouch
Mustapha Larhrouch

Reputation: 3393

the #my-signin2 must have an attribute type="button" because when you dont set the type. by default it submit

Upvotes: 2

Related Questions