POST returned value to MongoDB onsubmit

Viewed 129

I have a node express setup that saves values inputted into various checkboxes and text areas into a MongoDB database. Originally, you could also use checkboxes to calculate a score upon a button click as well as click another button to post the information like so:

new.ejs code

  <form action="/pipelines" method="POST">
    <%- include('_form_fields') %>
  </form>

_form_fields.ejs code

<div id="main_content_wrap" class="outer">
<section id="main_content" class="inner">
<div>
      <p>Information</p>
      <label for="url">GitHub URL:</label>
      <input required value="<%= pipeline.url %>" type="text" name="url" id="url"><br>

      <input type="checkbox" id="exampleCheck" name="exampleCheck" value="<%= pipeline.exampleCheck? 'checked' : '' %>"  onclick="checkboxTicked('exampleCheck', 3.5)">
      <label for="exampleCheck">Example Check</label><br>

      <button type="button" id="myCheck" onclick="splitURL(document.getElementById('url').value)">Calculate Score</button>
      <button type="submit" class="btn btn-primary">Save</button>
</div>
</section>
</div>

I have since tried to combine the myCheck button and the submit button into a single button.

new.ejs code

  <form action="/pipelines" method="POST" onsubmit="splitURL(document.getElementById('url').value)">
    <%- include('_form_fields') %>
  </form>

form_fields.ejs code

<div id="main_content_wrap" class="outer">
  <section id="main_content" class="inner">
<div>
      <p>Information</p>
      <label for="url">GitHub URL:</label>
      <input required value="<%= pipeline.url %>" type="text" name="url" id="url"><br>

      <input type="checkbox" id="exampleCheck" name="exampleCheck" value="<%= pipeline.exampleCheck? 'checked' : '' %>"  onclick="checkboxTicked('exampleCheck', 3.5)">
      <label for="exampleCheck">Example Check</label><br>

      <button type="submit" class="btn btn-primary">Save</button>
</div>
</section>
</div>

I want to post the returned onsubmit value to mongodb. Something along the lines of value="<%= pipeline.score %> as seen in the checkboxs and inputs. What is the best way to achieve this?

1 Answers

When you submit a form, it submits. And consequently page refreshes. So you need to stop that behavior

function sendData() {
   event.preventDefault();
   const form = $(this)[0];
   let url = form.url.value

   //your code here. You can play with url

   $(form).submit();
}

$('.my-form').on('submit', sendData);

And your form

  <form action="/pipelines" method="POST" class="my-form">
    <%- include('_form_fields') %>
  </form>
Related