I am new to ajax/jquery and I am trying to send a variable with a post request with ajax/jquery to the server and then console log it.
But for some reason when I console log it again from the server it stays undefined, so how do I properly send it off and retrieve it?
Code inventory.js:
$('form').on('submit', function() {
var temp = {test: 0}
$.ajax({
type: 'POST',
url: '/inventoryactionbtn',
data: temp,
success: function(data) {
//do something with the data via front-end framework
}
});
return false;
})
Index.js:
router.post('/inventoryactionbtn', ensureAuthenticated, function(req, res) {
var testing= req.body
console.log(testing)
})
There are three problems:
$('inventoryactionbtn')
Will match <inventoryactionbtn>
elements which aren't allowed in HTML. Probably you intended that to be an ID or class selector so you need the appropriate prefix.
submit
events only fire on <form>
elements so since you are targetting something with btn
in the name, you are probably targetting the wrong element anyway.
See the API reference :
Contains key-value pairs of data submitted in the request body. By default, it is
undefined
, and is populated when you use body-parsing middleware such asexpress.json()
orexpress.urlencoded()
.
There's no sign of any body-parsing middleware in the code you've provided. You need to use some which matches the format of the data you are POSTing.
/http://localhost:5000/inventory
, even if you remove the /
at the front, doesn't match (wherever you have mounted the router +) /inventoryactionbtn
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.