0

So I'm making an API call and one of the objects within that call is a unique ID. I'm trying to pass that ID object back server side using Ajax. It's not working. What am I doing wrong?

Here is my client side code, first I loop through a javascript object:

<% apiResultsdata['items'].forEach(function(items) { %>

    <% let ID = items['id'] %>
    <% let volumeInfo = items['volumeInfo'] %>
    <% let author = volumeInfo['authors'] %>
    <% let title = volumeInfo['title'] %>
    <% let image = null %>
    <% if(!(volumeInfo['imageLinks'] === undefined)) { %>
      <% image = volumeInfo['imageLinks']['smallThumbnail'] %>
 <% } %>

ID is what I need to pass back to nodejs after a link is clicked:

<div class="col">
                <div class="card-block px-2">
                  <a  href="/bookDetails"><h5 class="card-title"><%= title %></h5></a>


                  <script type="text/javascript">
                      $('a').click(function() {
                        $.ajax({
                          type: 'post',
                          data: {'ID':'<%= ID %>'},
                          url: 'localhost:3000/bookDetails',
                          success: function(data){
                            console.log('success');
                          }
                        });
                      });
                  </script>

In my data filed, I'm passing ID as a ejs object because that's the templating language I'm using. Not sure if that's right.

Here is the post route on the server:

router.post('/bookDetails', (req, res) => {
  let ID = req.query.ID;
  console.log('ID: ' + ID);
});

1 Answers1

0

You need to set contentType and JSON.stringify the object before passing to the data field. (check this thread)

$.ajax({
    type: 'post',
    contentType: "application/json; charset=UTF-8",
    data: JSON.stringify({ ID: '<%= ID %>' }),
    url: 'localhost:3000/bookDetails',
    success: function(data) {
        console.log('success');
    }
});

And it's always a good idea to use a json-parser middleware on the server side

const bodyParser = require('body-parser');
app.use(bodyParser.json());

Then you can get the request body that contains the ID parameter as follows

router.post('/bookDetails', (req, res) => {
  let ID = req.body.ID;
  console.log('ID: ' + ID);
});
Shant Marouti
  • 1,295
  • 7
  • 11
  • thanks. For some reason, it still doesn't work. After sitting up body-parser this is how I'm using it in my post route: 'let ID = req.body' you think this is right? – Rocky Singh Aug 13 '18 at 21:50
  • `req.body` is the object that contains the `ID` field. Try `req.body.ID` instead. `let ID = req.body.ID` – Shant Marouti Aug 13 '18 at 22:24