I am trying to use ajax to send data from client-side to server-side without refreshing the page.
I am using this ajax code inside my pug file -
script.
$(function() {
$('#form1').submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: {form.serialize()}
});
});
});
I am using the same URL and the method(which is POST).
Router file:-
const express = require("express");
const main_controller = require("../../controllers/main-controller");
const router = express.Router();
router.post('/form', main_controller.Send);
module.exports = router;
Controller file:-
const data_model = require('../../models/data-model');
exports.Send = (req, res, next) => {
data_model.find((err, data) => {
res.render("./customer/form1", {
pageTitle: "Form1",
data: data
});
});
};
I want to filter the data I am sending above. In the form, I have dropdown boxes in which I'm displaying the data, when the user selects something, I am sending the option he chose to the server. In the server, I am filtering data based on the option that was selected. I want to send the filtered data back to the client-side, but I am not able to.
In jQuery, you can use the success callback or the .done Promise Resolution for accessing data sent back by the server for further processing. Please have [a look here at the documentation][1] for further examples on how to do this.