Naheem Olaniyan
Naheem Olaniyan

Reputation: 93

Using $.ajax post to send data to node.js server not working

My goal is to convert a table date into array and send the array to the server side using Ajax post. This is my first time using Ajax post and i have followed all the answer in previous post. I don't still know what am missing. I am using body-parser to get the data on the server side. I will appreciate any assistance or if there is another easier way to send array to server side. My current output in undefined when I tried to print the output. Please see my code below:

ejs side

<table id="cartGrid">
        <thead>
             <tr>
                <th>Item Description</th>
                <th>Qty</th>
                <th>Unit Price</th>
                <th>Ext Price</th>
             </tr>
        </thead>
        <tbody>
          <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td>
          <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td>
   </tbody>
</table>

<script>
// convert table to array

    var myTableArray = [];
    $("table#cartGrid tr").each(function() { 
    var arrayOfThisRow = [];
    var tableData = $(this).find('td');
    if (tableData.length > 0) {
        tableData.each(function() { arrayOfThisRow.push($(this).text()); });
        myTableArray.push(arrayOfThisRow);
    }

// post the data
$.ajax({
        url: "/saler",
        type: "POST",
        data: myTableArray,
    });

});

</script>

server side

router.post('/saler', function (req, res, next) {
  var myTableArray = req.body.myTableArray;
  console.log(myTableArray);
});

app.js

app.use( bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Upvotes: 1

Views: 53

Answers (1)

Hank X
Hank X

Reputation: 2044

there is no myTableArray in your request body.

unless when you sending data you do this:

$.ajax({
        url: "/saler",
        type: "POST",
        data: {myTableArray},
    });

});

then you can do req.body.myTableArray to read the myTableArray.

try console.log(req.body) first to check the data struct in your request.

Upvotes: 1

Related Questions