Trung Tran
Trung Tran

Reputation: 13721

How can I AJAX POST an array of objects to a node.js server?

Is there a way I can ajax post an array of objects and have it parsed on a node.js server? Here is my client side code:

var context = [];

obj1 = {
      first_name: 'e',
      last_name: 'e',
      contact_email: 'e',
      contact_phone_num: 'e',
      contact_notes: 'e' 
  }


  obj2 = {
      first_name: 'a',
      last_name: 'a',
      contact_email: 'a',
      contact_phone_num: 'a',
      contact_notes: 'a' 
  }


  var context = [];

  context.push(obj1);
  context.push(obj2)


  $.ajax({
    type: "POST",
    url: '/api/addcontact',
    data: context,
    success: function(data, status) {
        alert('company added!');

    },
    error: function(data, status, res) {
        console.log('err: ' + res);
    }
});

My server side code:

api.post('/api/addcompany', function(req, res) {
    console.log('add company hit');
    console.log(req.body);  //returns {}
    res.sendStatus(200);
});

Right now, when I print the request body it returns {}.

Can someone help me access the array of objects properly on the server side?

Thanks in advance!

Upvotes: 1

Views: 661

Answers (2)

thedeliciousmuffin
thedeliciousmuffin

Reputation: 814

First of all, you should remove one of the context variables. There's no need for the second one when you have declared it already at the top.

Second, it seems like you're posting to the wrong url, should it be /api/addcompany or /api/addcontact?

Upvotes: 0

shamsup
shamsup

Reputation: 2022

This is happening because you aren't sending an object inside of your ajax post, you're sending an array. Try wrapping the array in {} to signify that it's indeed an object, then reference that object property in your server code.

var context = []; // array

  context.push(obj1);
  context.push(obj2)


  $.ajax({
    type: "POST",
    url: '/api/addcontact',
    data: {context: context}, // requires an object here
    success: function(data, status) {
        alert('company added!');

    },
    error: function(data, status, res) {
        console.log('err: ' + res);
    }
});

Then in your server-side script, you can reference the context property of the body object.

Upvotes: 1

Related Questions