0

I am trying to make a post request using AJAX request, to be able to store it in the database. I have a button using the onclick event to call the usernameCheck() function, inside of my bundle.js file created with browserify. My DataController.js file includes the add function I am using to add the username to the database. When I click the button after typing in my username, there is a connection to the database but the value for the body is undefined

usernameCheck()

      function usernameCheck() {

        var user = document.getElementById('userbox').value;
        //var Filter = require('bad-words');
        //var filter = new Filter();

        var username = JSON.stringify(user);

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
          if (this.readyState == 4 && this.status == 200) {
            console.log("RESPONSE TEXT: " + this.responseText);
          }
          else {
            console.log("FAILED\nReady State: " + this.readyState + "\nStatus: " + this.status);
          }
        };
        xhttp.open("POST", "/add", true);
        xhttp.send(username);

DataController.js

module.exports = {

    add: function (req, res) {
        var user = req.body.username;
        console.log(user);
        console.log(req.param());

        Data.create({ username: user }).exec(function (err) {
            if (err) {
                res.send(500, { err: 'Database Error' });
            }
            else {
                console.log("WORKS");
                return res.ok();
            }
        })

    }

};

This is how I have the route set up 'POST /add': 'DataController.add'

Message I get back

Bash and console

FAILED
Ready State: 1
Status: 0

FAILED
Ready State: 2
Status: 200

FAILED
Ready State: 3
Status: 200

RESPONSE TEXT: OK
XHR finished loading: POST "http://localhost:1337/add".

Database

[
  {
    "createdAt": 1592347252042,
    "updatedAt": 1592347252042,
    "id": "5ee94a7496f3a93aece14da3",
    "username": ""
  }
]

1 Answer 1

1

I don't often send these requests without jquery, but I'm fairly sure you're not sending your data in the right format.

The data you send should have a "key" and a "value" I think just xhttp.send(username); is sending a key with no value.

Try xhttp.send({username: username}); and see if that works. The first 'username' is the name you are giving the key, and the second is passing in the json from your variable as the value.

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

1 Comment

Such a small thing I've done alot of times but didn't even notice. Your syntax didn't work, but it made me realize my mistake. I changed my var username --> var username = JSON.stringify({ "username": user });

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.