Here is the form and addingTask() function.
<form method="GET" action="/newtask" onsubmit="addingTask()">
<label> Today's Task: </label><br>
<input type="text" id="task"><br>
<button type="submit">Add</button>
</form>
<script>
function addingTask() {
var data = {
task: $("#task").val(),
}
$.ajax({
type: "GET",
url: "/newtask",
dataType: 'JSON',
data: data,
success: function success(result) {
console.log("iiiiiiiiiiiii", result);
console.log("565656565656565");
},
error: function error(error) {
console.log("sdsdsdsdsd", error);
console.log("mmmmnnnnmmmnnn");
}
})
}
</script>
This is the route file.
var express = require('express');
var router = express.Router();
const indexController =
require("../controllers/indexController");
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'To-Do-List' });
});
router.get('/newtask', indexController.createTask
);
module.exports = router;
This is the controller function file.
const createTask = (req, res, next) => {
console.log(req.body);
var variable = JSON.stringify(req.body);
res.render('index', { title: variable });
};
module.exports = { //A module means file
createTask
}
Initial Screen https://i.stack.imgur.com/itWPX.png
After filling the form and on clicking the add button i get empty title https://i.stack.imgur.com/AqIWf.png
I have tried changing http method to 'POST' but still the same error occurs.
The "type" key inside $.ajax() should be 'POST' and also in the router file it should be router.post and finally, inside controller function file it should be res.send({data: req.body.task}); instead of res.render(index, { title: variable });