Babak Rz
Babak Rz

Reputation: 41

$.ajax post doesn't post data (JavaScript)

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.

Upvotes: 0

Views: 517

Answers (1)

rie
rie

Reputation: 296

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"?

Upvotes: 1

Related Questions