4

I need to send a js object to the server through ajax request; is an object containing parameters for a sql query with Sequelize orm in node js; an example is like this:

var data =
{
    include: [
        { model: model.Shop },
        { model: model.Product,
            include: [
                { model: model.File }
            ]
        }
    ]
}

It can contain arrays of objects nested on multiple levels; before sending it I can convert it to valid JSON if needed, like this:

var data =
{
    "include": [
        { "model": "model.Shop" },
        { "model": "model.Product",
            "include": [
                { "model": "model.File" }
            ]
        }
    ]
}

I've tried to send it as JSON:

$.ajax({
    //...
    data: data
});

The problem is that when in the node server I do JSON.parse of the received string, the value of each property is a string and it is not recognized as a model object;

How can I make my server able to understand this?

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • *"I can convert it to valid JSON if needed, like this"* That's not JSON, that is still a JavaScript object. `{"foo": 42}` is the same as `{foo: 42}`. – Felix Kling Jul 11 '14 at 06:58

2 Answers2

5

Try to use JSON.stringify

$.ajax({
    data: JSON.stringify(data)
});
Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
  • Ok, the problem is that I'm trying to send in headers "model.Shop" that is not defined in the Ember client (it's defined in the node server); so I think there's no way to do it; probably I should send a string and then write a function to parse it in the node server... – Cereal Killer Jul 16 '14 at 02:05
  • it's not working with `Map` – Amol Bais Oct 21 '19 at 11:43
0

Don't put manually quotes to your data object.

try

JSON.stringify(data)

It will convert that to acceptable string format.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68