I am trying to insert data in my database when I click an element, on the element I got a function which gets some data from it. Then I want to insert that data + some more to my database, like this:
function insertItem(x)
{
var Aktiv = "Bokad";
var tid = x.dataset.tid;
var dag = x.dataset.dag;
var namn = "Filip";
var url = '/insert/' + Aktiv + '/' + tid + '/' + dag + '/' + namn;
$.ajax({
url: url,
type: 'POST',
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
});
}
Then in my node file I think I should retrive it like this:
app.post('/insert/:Aktiv/:dag/:namn/:tid', function(req, res){
pool.connect(function(err, bokad, done){
if(err){
return console.error('error fetching bokad inserted', err);
}
bokad.query("INSERT INTO bokad(aktiv, dag, namn, tid) VALUES($1, $2, $3, $4)",
[req.body.Aktiv, req.body.dag, req.body.namn, req.body.tid]);
console.log(req.body.Aktiv);
done();
res.redirect('/');
});
});
Element I click contains this
<td onclick = "insertItem(this)" data-dag = "<%= bord.rows[19].dag %>" data-tid = "<%= bord.rows[19].tid %>" class = "<%= bord.rows[19].Aktiv %>"></td>
In your post route you can see that you declared parameter variables: :Aktiv. You would also have to do this with dag, namn, tid. with a : before it.
There are multiple ways of sending information with a http request. I would not do this with params. But I would put it in the body of your request and access it with req.body[variabel]. If you would send your variables in the body of the POST request please do not forget to add your body parsers, if it would be a normal form: http://expressjs.com/en/api.html#express.urlencoded , if it would be as JSON: http://expressjs.com/en/api.html#express.json
If you want to do it with params you have to access them with req.params[variable name], eg: req.params.Aktiv.
I suggest reading: https://expressjs.com/en/guide/routing.html#route-parameters and https://expressjs.com/en/4x/api.html#req.params
Good luck. I hope this helped.
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.