简体   繁体   中英

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

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM