fkushgvosvu
fkushgvosvu

Reputation: 3

how to send POST request and get back response without the page loads with NodeJS

I want to send a post request to my NodeJS server to update a document in my database and get back the response, but I don't want the page loads, I just want to alert it that the process has been successfully done ..... here is my code HTML:

 <form action="/products/update" method="POST" id="myFrom">
                        <button type="submit" class="btn btn-success">save</button>

    <input type="number" name="productCount">

    <input type="text" name="productName">
</form>

JS:

$("#myFrom").submit(function (e) {
    $.ajax({
            success: function (data) {
                console.log(data);
            }
    });
});

NodeJS:

router.post("/products/update", (req, res) => {
    console.log(req.body);
    res.status(200).send("success");
});

the poblem is when i press save it redirects to /products/update and types success in it, but i want the success to be an alert in the editing page

Upvotes: 0

Views: 742

Answers (1)

Ashish Mishra
Ashish Mishra

Reputation: 422

User e.preventDefault() to submit form without refreshing the page

 $("#myFrom").submit(function (e) {
 e.preventDefault()
 $.ajax({
        success: function (data) {
            console.log(data);
        }
  });
 });

Upvotes: 3

Related Questions