Pass js object with ajax request

19,632

Try to use JSON.stringify

$.ajax({
    data: JSON.stringify(data)
});
Share:
19,632
Cereal Killer
Author by

Cereal Killer

No way as a way, no limit as a limit... What you can't do alone, we'll do together...

Updated on August 21, 2022

Comments

  • Cereal Killer
    Cereal Killer over 1 year

    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
    Cereal Killer almost 10 years
    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...
  • Amol Bais
    Amol Bais over 4 years
    it's not working with Map