JavaScript form fetch request submitting empty values when they are filled in

I am creating a Login form in JavaScript and am trying to send this form to my Ruby on Rails backend.

I have two problems:

  1. When the form loads, it triggers the eventListener and sends the blank form’s data to the backend. I have e.preventDefault() commented out in the second function below because I kept getting the error that it is not a function. Note: in the backend for Rails, I get the following message when I type in params. "Permitted: false" concerns me.
    <ActionController::Parameters {"controller"=>"sessions", "action"=>"create", "session"=>{}} permitted: false>

  2. When I fill in the form with an email and password and click the submit button, the loginData (from loginButton.addEventListener("submit", submitLogin(loginData) submits a blank value for the email and ‘password’ for the password (which are the default values I set to test the values) even though these elements are filled in in the form with an actual email address and password.

Function loading login form (note: this loads just fine):

  // create the elements
  var div = document.createElement("div"),
    log = document.createElement("div"),
    loginForm = document.createElement("form"),

  //set form attributes
  loginForm.setAttribute("method", "POST");

  // set body styles
  document.body.style.textTransform = "capitalize";

  log.id = "login";
  log.innerHTML = "login";

  // set loginForm styles
  loginForm.id = "loginForm";

  // set the elements and styles on the form
  loginForm.innerHTML =
    "<label>username</label><br/>" +
    "<input type='text' id='login-email' value='' placeholder='email' style='" +
    inputStyles +
    "' /><br/>" +
    "<label>password</label><br/>" +
    "<input type='password' id='login-password' value='value' placeholder='*************' style='" +
    inputStyles +
    "' /><br/>" +
    "<input type='submit' id='login-button' value='Login' style='" +
    btnStyles +
    "' />" +
    "<p><a style='" +
    forgetStyles +
    "' href='#'>forget password ?</a></p><br/>";
 
  // append the buttons and form on main-div
  div.appendChild(log);
  div.appendChild(loginForm);

  // append main-div on the body
  document.body.appendChild(div);

  //get login form values to submit
  let loginEmail = document.getElementById("login-email").value;
  let loginPassword = document.getElementById("login-password").value;
  let loginData = { member: { loginEmail, loginPassword } };
}

SubmitLogin Function (fetch request to Rails backend):

async function submitLogin(e) {
  // e.preventDefault();
  const loginData = new FormData(e.target);
  debugger;
  let options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin":
        "file:///Users/awb/Coding/Flatiron/Projects/bookclub-javascript-rails-api/bookclub-frontend-javascript/index.html",
      "Access-Control-Allow-Methods": "POST",
      "Access-Control-Allow-Headers": "Content-Type, Authorization",
      Accept: "application/json",
    },
    body: JSON.stringify(loginData),
  };

  fetch("http://localhost:3000/login", options)
    .then((resp) => {
      resp.json();
    })
    .then((member) => {
      console.log(member);
      return new Member(member);
    });
}

If it matters, this is the order of my scripts at the bottom of my index.html page:


    <script src="src/suggestion.js"></script>
    <script src="src/member.js"></script>
    <script src="src/gathering.js"></script>
    <script src="src/book_group.js"></script>
    <script src="src/book.js"></script>
    <script src="src/login_registration_form.js"></script>
    <script src="src/index.js"></script>

Where index.js calls the function "loadRegistrationLogin()" as the last line on index.js

My routes are:

Rails.application.routes.draw do
  resources :members, only [:create, :index, :show]
  resources :registrations, only: [:create]
  resources :sessions, only: [:create]
  
  post '/login', to: 'sessions#create'
  delete '/logout', to: 'sessions#destroy'
  get '/logged_in', to: 'sessions#is_logged_in?'

  root to: "static#home"
  
end

and finally, my session controller:

class SessionsController < ApplicationController
    include CurrentMemberConcern
    skip_before_action :verify_authenticity_token

    def create
        member = Member
        .find_by(email: params[:member][:email])
        .try(:authenticate, params[:member][:password])

        if member 
            login!
            render json: {
                status: :created, 
                logged_in: true,
                member: member 
            }
        else 
            render json: { 
                status: 401,
             errors: ['No such member', 'Verify credentials and try again or sign up']
            }
        end
    end
end

142 thoughts on “JavaScript form fetch request submitting empty values when they are filled in”

  1. After going over a few of the blog articles on your web site, I truly
    like your way of blogging. I book marked it to my bookmark website list
    and will be checking back in the near future. Please visit my web site
    too and let me know your opinion.

    Reply
  2. Fantastic goods from you, man. I have understand your stuff previous to and
    you’re just extremely great. I really like what you’ve acquired here, really like what you’re stating and the way in which you say it.
    You make it enjoyable and you still take care of to keep it sensible.
    I can’t wait to read much more from you. This is really
    a tremendous website.

    Reply
  3. Excellent beat ! I wish to apprentice while
    you amend your site, how could i subscribe for a
    blog site? The account aided me a applicable deal. I had been a little
    bit acquainted of this your broadcast offered bright transparent idea

    Reply
  4. Hey there, You’ve done an incredible job. I will definitely digg it and personally suggest to my friends.
    I am sure they’ll be benefited from this web
    site.

    Reply
  5. Have you ever considered writing an e-book or guest authoring on other websites?
    I have a blog based upon on the same subjects you discuss and would love to have you share some stories/information. I
    know my viewers would value your work. If you’re even remotely interested, feel free to
    send me an e mail.

    Reply
  6. It’s appropriate time to make a few plans for the longer term and it’s time to be happy.
    I have learn this publish and if I may I desire to suggest you some fascinating things or advice.
    Maybe you could write next articles regarding this
    article. I want to learn even more issues approximately it!

    scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

    Reply
  7. I’m amazed, I must say. Seldom do I come
    across a blog that’s both educative and amusing, and let me tell you, you’ve hit the nail on the head.
    The issue is something which too few people are speaking intelligently about.
    I’m very happy that I came across this during my hunt for something relating to this.
    ps4 games https://bit.ly/3z5HwTp ps4 games

    Reply