简体   繁体   中英

How to send response to ajax post request in express node.js?[answered]

I'm doing a simple project to practice node js along with Jquery Ajax. So I have an ajax post request that sends some data to nodejs server and wait for a response. In the server-side, I have a code that reads the data and do something with it. This works fine. But when I try to send the response back to ajax, the page changes and it shows the response in plain text. What I want is to do something with the response in ajax side. Sorry if I'm not clear, but hope you understand when reading the code.

Jquery Ajax code:

$("submitBtn").on("click", e=>{
        e.preventDefault();
        $.ajax({
            url: "/getCity",
            type: "POST",
            data: `city=${cityName}&country=${countryName}`,
            success: function(data){
                console.log(data);
            }
        });
    });

server-side code:

app.post("/getCity", (req, res)=>{
    //a promise
    .then(cityID=>{
        res.status(200).send(cityID.toString());
        });
});

html code:

<form method="post" action="/getCity">
    <input/>
    <input/>
    <button id="submitBtn" type="submit">Search Weather</button>
</form>

I included html code because I don't know if putting method="post" action="/getCity" is necessary even though making the ajax post request. I hope you help me with this and if possible the html thing. Thank you in advance. NOTE: This question is a recreation of another question I asked before. I did it because it was marked as a duplicate, but after that it was answered by another user, only in a comment, who asked to do so in order to benefit others from it in the future.

Please use it as following in your html file. Should solve your problem

<body>
    <form method="post" id="cityform">
        <button id="submitBtn" type="submit">Search Weather</button>
    </form> 
</body>

<script>
    $("#cityform").submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: "https://localhost:8443/getCity",
            type: "POST",
            data: {
                'city': 'pune',
                'country': 'India',
            },
            success: function(data){
                console.log(data);
            }
        });
    });

</script>

Post request should look like this, I'm calling some function as findCity, you don't have to use it.

app.post("/getCity", (req, res) => {
    var cityname= req.body.city;
    var country= req.body.country;
    city.findCity(cityname, country).then((cityID) => {
        res.status(200).send({ cityID: '123' });
    }).catch((e) => {
        res.status(400).send(e);
    });
});

In the duplicate, they discuss how it's possible for the DOM selector to fire before the element is on the page. That's not quite your issue. You're missing the # part of your selector (since you're selecting by ID). Change your first line of your AJAX to $("#submitBtn").on("click", e=>{ and it will work. Because this was erroneously marked as a duplicate, I wasn't able to post this as an answer. If this solution works, please create your question again, provide my comment as an answer, and accept it, so that others will be able to benefit from it in the future. @Welkie

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