I'm having issues calling an Express route in my Node.js app from Ajax when a form is submitted.
My route looks like this:
router.post("/user", function(req, res) {
console.log("FORM DATA: " + JSON.stringify(req.body));
res.send('done!');
});
My Ajax call looks like this:
$("#add-report-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
uri: "/user",
contentType: "application/json",
data: JSON.parse(JSON.stringify($("#add-report-form").serializeArray())),
}).done(function(data) {
alert("ajax call done!");
});
});
I have the following in my app.js app.use(bodyParser.json());
.
When I submit my form, the console.log in my route does not run and I can't figure out why, it seems the route in is not getting called at all. Any help would be great!
My form looks like this:
<div class="modal-body">
<form id="add-report-form">
<div class="row">
<div class="col">
<label for="report-select">Report</label>
<select class="form-control" id="report-select" name="report">
<option>Select Report</option>
</select>
</div>
</div>
<div class="row modal-row">
<div class="col">
<label for="interval-select">Report Interval</label>
<select class="form-control" id="interval-select" name="interval">
<option>Select Interval</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="add-submit" class="btn btn-primary save-changes">Save changes</button>
</div>
</form>
</div>
I also tried executing the Ajax on the click event of the button, but still no luck, the alert pops up but the route is still not called.
$("#add-submit").on("click", function(e) {
alert("this is the form submission");
e.preventDefault();
$.ajax({
type: "POST",
uri: "/user",
contentType: "application/json",
// data: JSON.parse(JSON.stringify($("#add-report-form").serializeArray())),
data: JSON.stringify({data: "test"}),
}).done(function(data) {
alert("ajax call done!");
});
});
The problem might be a typo. Try 'url' instead of 'uri':
$.ajax({
type: "POST",
url: "/user",
contentType: "application/json",
// data: JSON.parse(JSON.stringify($("#add-report-form").serializeArray())),
data: JSON.stringify({data: "test"}),
}).done(function(data) {
alert("ajax call done!");
});
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.