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.
console.log(posthash);prints properly?document.getElementById('hashtag')todocument.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