1

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 }));

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it works. But I have an issue of the post working immediately when I load the page. Please how can I prevent this? I prefer it to only work when I click a button. Thanks.
@NaheemOlaniyan add a button in your page. add click event listener to it, <button onclick=postMethod>Send</button>. postMethod is where you call $.ajax
Got it. Thanks so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.