Issue
I'm a beginner so I don't know if I was clear with my question. My problem is that the response I send from my express server shows in the page but I can't handle it in my client side using jQuery.
Server-side:
router.post("/", [
//check inputs using expres-validator
],
(req, res)=>{
//handle validation results
var errors = validationResult(req);
if (!errors.isEmpty()) {
//filter errors
res.status(400).send([usernameErr, emailErr, passwordErr]);
}else {
res.sendStatus(200);
};
});
client-side:
$(".form-div form input[type='submit']").submit(function(e){
e.preventDefault();
if($(this).parent().parent().attr("id") == "signup-form-container"){
$.post('/signup', $('#signup-form-container form').serialize())
.done(data=>{
alert(data)
console.log(data);
})
.fail((err, textStatus)=>{
alert(err)
console.log(err)
});
};
});
I'm exporting my signup file, which have the route above, to my main file.
app.use("/signup", require(`${__dirname}/routes/signup.js`));
Solution
So if you check your selector:
$(".form-div form input[type='submit']") // this is selecting the input element
However, the submit event only fires when it is inside the form element, so attaching the submit event to buttons, or inputs will not work.
Here is the reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
So, to solve the problem, try this:
/*
Here you are selecting the form, so submitting here will work.
*/
$(".form-div form").submit(function(e){
e.preventDefault();
if($(this).parent().parent().attr("id") == "signup-form-container"){
$.post('/signup', $('#signup-form-container form').serialize())
.done(data=>{
alert(data)
console.log(data);
})
.fail((err, textStatus)=>{
alert(err)
console.log(err)
});
};
});
That's the reason that click was working because that fires when you click the element. I hope this makes sense.
Answered By - German Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.