0

I'm using Ajax in my Node.js & Express website in order to send a value from a text box to the server side. Right now, it is working; the req.body has the text value that I need, however the JSON is formatted in a way that is difficult for me to get the value. In short, it seems my ajax is renaming the variable name to the value entered within the text box. So instead of the req.body being

{ hashtag: 'test123' }

The req.body shows:

{ test123: '' }

E.g: In my Jade file:

         form
            input#hash(type='text', name='hashtag[hash]', placeholder='#Hashtag')
            input#submit.btn.btn-primary(name='submit', type='submit', value='Send', onclick='return chk()')

    p#msg


script.
  function chk(){
    var posthash = document.getElementById('hashtag').value;
    console.log(posthash);
    $.ajax({
        type:"post",
        url: "/api/hash",
        data:posthash,
        cache:false,
        success: function(html){
            console.log("Successfully posted");
            $('#msg').html(html);
        },
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
            console.log(error);
        }
    })
  return false;
  }

Then, within my server.js:

app.post("/api/hash", function (req, res) {
  console.log(req.body);
});

So, if I enter this into the text box:

test123

The req.body shows:

{ test123: '' }

As you can see, the variable name itself is the value of the text box. Thus, if I try to say console.log(req.body.hashtag) or console.log(req.body.hash), it comes up as undefined - because that's not the variable name.

3
  • console.log(posthash); prints properly? Commented Mar 5, 2017 at 13:20
  • @AndreaM16 Yes, if I change document.getElementById('hashtag') to document.getElementById('hash') it prints properly. At the moment, document.getElementById('hashtag') doesn't actually work, as it can't find that value for some reason... I changed it to hashtag to test Commented Mar 5, 2017 at 13:29
  • To me it seems like your post is fine but you are sending an empty string. Try taking a look. Commented Mar 5, 2017 at 13:30

1 Answer 1

1

The problem is the way you submit the posthash. This variable contains the string you enter in the input,but $.ajax is expecting an object as data option. Just change the line like this :

 data: {hashtag: posthash} ,

And since you declare the input with hash as id

input#hash

you have to use

document.getElementById('hash').value;

to get it's value.

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

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.