2

I'm trying to learn how to send data using ajax. When the submit button is clicked, I want Ajax to send the data to a particular route, unrelated to the data and a route associated with the form. However, Ajax doesn't seem to be sending anything. I added three console.log() statement in my script but none of them are being displayed.

HTML and AJAX code

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  <form class="" action="/submitData" method="post">
    <input type="text" name="name">
    <button id="submitForm" type="submit">Submit</button>

    <script>
      const el = document.getElementById(submitForm);
      if (el) {
        el.addEventListener('submit', addRecipe);
        console.log('Step 1');
      }


      function addRecipe() {

        var recipe = {
          param1: 'value1',
          param2: 'value2'
        };

        console.log('step 2')

        let xml = new XMLHttpRequest();
        xml.open("POST", "/add-recipe", true);
        //Specify the type of data to be sent
        xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xml.send(JSON.stringify(recipe));
        console.log('step 3');
        }
    </script>
</body>

</html>

server.js file

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let urlencodedParser = bodyParser.urlencoded({extended: false});

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(7000);

app.post('/add-recipe', function(req, res) {
  var recipe = req.body.recipe;
  console.log(recipe);
});

app.post('/submitData',urlencodedParser,function(req, res){

});

2 Answers 2

2

You need to add type="button" to your submit button and use preventDefault to make xmlhttp request...

const el = document.getElementById("submitForm");
      if (el) {
        el.addEventListener('click', addRecipe);
        console.log('Step 1');
      }


      function addRecipe(e) {
        e.preventDefault();
        var recipe = {
          param1: 'value1',
          param2: 'value2'
        };

        console.log('step 2')

        let xml = new XMLHttpRequest();
        xml.open("POST", "/add-recipe", true);
        //Specify the type of data to be sent
        xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xml.send(JSON.stringify(recipe));
        console.log('step 3');
        }
<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  <form class="" action="/submitData" method="post">
    <input type="text" name="name">
    <button id="submitForm" type="submit" type="button">Submit</button>

  </form>
</body>

Sign up to request clarification or add additional context in comments.

1 Comment

I never knew you could have more then one type attached to one element. Thank you. However, can up update you answer an explain why attaching type ="submit to both the form and the even listener isn't working? Also, can you please explain what e.preventDefault(); does an why it's need?
1

Actually when the submit button is clicked, the form will be submitted, so the page/data will be directly redirected to the action page.

That's why your addRecipe() function is not executed because the page is redirected before its execution.

So if you want to execute the addRecipe() function and send the data via Ajax before submitting the form, you need to prevent the default form submition, execute your code and then submit the form:

function addRecipe(e) {

    e.preventDefault();

    var recipe = {
      param1: 'value1',
      param2: 'value2'
    };

    console.log('step 2')

    let xml = new XMLHttpRequest();
    xml.open("POST", "/add-recipe", true);
    //Specify the type of data to be sent
    xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
    xml.send(JSON.stringify(recipe));
    console.log('step 3');

    //Get the form and submit it
    form.submit();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.