2

I'm trying to make an Ajax request, but my object keeps coming back as undefined.

Here's my client side code:

<a class="clicklink" href="/bookDetails"><h5 class="card-title"><%= title %></h5></a>

<script type="text/javascript">
$(document).ready(function(){
  $(".card-title").click(function(){
    $.ajax({
      type: 'post',
      contentType: "application/json; harset=UTF-8",
      data: JSON.stringify({ID:'<%= ID %>'}),
      url: 'http://localhost:3000/bookDetails',
      success: function(data){
        console.log('success');
      }
    });
  });
});
</script>

Here is my post request code:

router.post('/bookDetails', (req, res) => {
  console.log(req.body.ID);
});

BTW, I'm putting my <h5> tag inside a link so it's clickable. I don't maybe that's the problem but I don't think so. But this is the error I get back:

Cannot read property 'ID' of undefined

Any ideas? Thanks.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64

2 Answers2

1

If you're using Express, make sure you have the body-parser middleware enabled.

Related Post: Express.js req.body undefined

pfcodes
  • 1,055
  • 2
  • 9
  • 15
0

The error message tells you that the property cannot be read because the parent is undefined. One common cause of this is that the response from the ajax call is a string rather than an object. Have you checked the return type?

Adam Chubbuck
  • 1,612
  • 10
  • 27