0

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?

2
  • Well, is it working? Commented Dec 10, 2017 at 20:01
  • Can you see updated question please Commented Dec 12, 2017 at 17:45

3 Answers 3

1

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'
        });
Sign up to request clarification or add additional context in comments.

1 Comment

Can you see my question again please
1

You can also use jQuery short-hand methods.

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

Comments

0

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

Comments

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.