0

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.

Eye Patch
  • 459
  • 7
  • 17
  • Since `e.preventDefault();` isn't preventing the normal form submission, the event handler must be failing to bind. So see the duplicate… – Quentin Mar 24 '19 at 21:50
  • I visited the question you linked, but I can't understand how the response I'm trying to send from node.js is a DOM element. – Eye Patch Mar 25 '19 at 19:35
  • 1
    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. – Matt Welke Mar 26 '19 at 03:15
  • Yes it works. I was missing a lot of "#". Thank you for the help. – Eye Patch Mar 26 '19 at 14:03

0 Answers0