0

I can't figure out why this problem is arising. When I make an ajax post request in my javascript file, the url gets called, but the data wont get sent. Here's how I make a post request:

<script type="text/javascript">
    $.ajax({
        type: "POST",
        url: "/test",
        dataType: "json",
        data: {test: "test"},
        contentType: "application/x-www-form-urlencoded",

    });
</script>

And on my backend, here's the post method I'm using:

app.post('/test', function(req, res) {
  console.log(req.body); // returns {}
  console.log(req.params); // returns {}
});

Here's what I tried so far: XMLHttpRequest to Post HTML Form, AJAX Post not sending form data , Send POST data using XMLHttpRequest but unfortunately none of them worked for me.

Community
  • 1
  • 1
Babak Rz
  • 41
  • 9
  • 1
    you can remove the contentType option, that's not necessary for what you're doing. (the default will suffice) – Kevin B May 01 '17 at 19:53
  • You're sure you're hitting your endpoint? You're seeing stuff in your console on the server-side whenever you send an AJAX request? Have you tried doing `console.log(req)` to see if the data is on a different property? – Mike Cluck May 01 '17 at 19:53
  • try `JSON.stringify({test: "test"})` – Rohith K P May 01 '17 at 19:53
  • @KevinB I've tried it without contentType too, still doesn't work. Any other suggestions? – Babak Rz May 01 '17 at 19:54
  • you have to send some response to FE right? `res.send('something')` ?? otherwise that request will get timedout in browser – Rohith K P May 01 '17 at 19:54
  • Besides MikeC's advice, do you have something parsing the body? bodyparser maybe? – Kevin B May 01 '17 at 19:54
  • @MikeC Yes, the server side is being called and I am seeing {} on the server side console. – Babak Rz May 01 '17 at 19:55
  • @Mendax I tried JSON.stringify({test: "test"}), still not working – Babak Rz May 01 '17 at 19:56
  • @rie `dataType: "json" sends data in JSON` eh, no, that's not what dataType does. – Kevin B May 01 '17 at 19:56
  • @rie Wow, that worked! I'mm definitely sure I tried application/json before changing it to application/x-www-form-urlencoded. Somehow it's working now! If you post this as an answer, I will mark it correct. – Babak Rz May 01 '17 at 20:00
  • Why would you want to use Ajax request when you can actually post it directly using `"action"`attribute? – Ozan May 01 '17 at 20:02
  • @BabakRz Thanks! I`ve post it as answer. – rie May 01 '17 at 20:06

1 Answers1

1

dataType: "json" expects data in JSON, but contentType: "application/x-www-form-urlencoded" sends data in different way. Maybe you should write dataType: "json", contentType: "application/json" or dataType: "html", contentType: "application/x-www-form-urlencoded"?

rie
  • 236
  • 1
  • 4