Alice
Alice

Reputation: 243

How to send JS object as JSON correct?

I have the following JS Object:

json =
            {
                "category_id": category,
                "subcategory_id": subcategory,
                "offer_type": type_offer,
                "features": []
            };

I tried to send this object as JSON like:

$.ajax({
            type: 'POST',
            url: '/add',
            data: json,
            success: function (data) {
            },
            contentType: "application/json",
            dataType: 'json'
        });

Is it right? Or I need to make some preparations before?

Now I use this part of code:

formObj = $("#form_add").serialize();

var json = {};

var wrapperObj = {json: json, form: formObj};

    $.ajax({
                type: 'POST',
                url: '/add',
                data: JSON.stringify(wrapperObj),
                success: function (data) {
                   // TODO
                },
                contentType: "application/json",
                dataType: 'json'
            });

Is it right way? When I package two object inside one and after stringify?

Upvotes: 0

Views: 41

Answers (3)

jmshuck
jmshuck

Reputation: 11

You can also use jQuery short-hand methods.

$.post('/add', json).done(function() {
     // Handle response here
  });

Upvotes: 1

M.Boukhlouf
M.Boukhlouf

Reputation: 313

I think you should use JSON.stringify first:

$.ajax({
            type: 'POST',
            url: '/add',
            data: JSON.stringify(json),
            success: function (data) {
            },
            contentType: "application/json",
            dataType: 'json'
        });

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

You need to use JSON.stringify to make it a valid json

$.ajax({
            type: 'POST',
            url: '/add',
            data: JSON.stringify(json),
            success: function (data) {
            },
            contentType: "application/json",
            dataType: 'json'
        });

Upvotes: 1

Related Questions