简体   繁体   中英

AJAX Request POST data to rails controller gives 404

I want to post data to a rails controller via an AJAX request

My route: get "pki_login/authenticate" => "pki_logins#authenticate"

The JS:

$.ajax({
    type: 'POST',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

then inside pki_logins_controller.rb i have:

def authenticate
  puts params[:passcode]
end

the authenticate.html.erb file just contains a h3 tag.

I can visit /pki_login/authenticate and it works, but when accessing via AJAX I get a 404 so I don't even know if the POST works either

You're defining a get route but making POST request.

Try:

$.ajax({
    type: 'GET',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

Or change the route to post and use post ajax request as:

# config/routes.rb
post "pki_login/authenticate" => "pki_logins#authenticate"

Then the ajax call:

$.ajax({
    type: 'POST',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM