1

Trying to send a json data by GET.
Json data:

var data = {
    country: {
        name: "name",
        code: 1
    },
    department: {},
    cars: ["bmw", "ferrari"],
    books: []
}

Sending code:

var posting = $.ajax({
    url: "/do",
    type: "GET",
    traditional: true,
    data: data,
    dataType: "json"
});

posting.done(function (data) {
    // handle result
});

If traditional=true the (parsed, decoded) query string is

country[name]:name
country[code]:1
cars[]:bmw
cars[]:ferrari

If traditional=false the (parsed, decoded) query string is

country:[object Object]
department:[object Object]
cars:bmw
cars:ferrari

The desired one should be

country:{"name": "name", "code":1}
cars:bmw
cars:ferrari

or

country:{"name": "name", "code":1}
cars:["bmw", "ferrari"]

In other words, the empty objects and arrays should be omitted. The object should be encoded correctly. Tried with different contentType along with JSON.stringify() without luck. Is there a way to this?

5
  • try data = encodeURIComponent(JSON.stringify(data)); before ajax call Commented Aug 6, 2015 at 11:16
  • sorry try this, this will remove empty objects: try data = $.param(data);before ajax call Commented Aug 6, 2015 at 11:29
  • stackoverflow.com/questions/23774231/….. Almost same question, though the answer did not work for me as per required by you..So i wrote mine.. Please make the question title general as my function in answer removeFirstLevelEmptyPropertiesFromJSON . However i could do it recursive if you need it Commented Aug 6, 2015 at 13:29
  • Thank you @Sami for your effort. I already realized that I need to write code to remove empty attributes, and using $.isEmptyObject for that. Commented Aug 6, 2015 at 13:32
  • @Farhan thanks for your input. I totally changed the logic of sending data to the server, and actually this question is obsolete anymore. Commented Aug 6, 2015 at 13:33

3 Answers 3

1

As per my understand what I understand question is to send multidimensional json array in url. I have test following code on local host. Hope this will help you. I am so junior then your reputation but just trying to help

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
var data = {
    country: {
        name: "name",
        code: 1
    },
    department: {},
    cars: ["bmw", "ferrari"],
    books: []
}

    data = $.param(data);

    var posting = $.ajax({
        url: "test.php",
        type: "GET",
        traditional: true,
        data: data,
        dataType: "json"
    });

    posting.done(function (data) {
        console.log(data);
    });
    </script>

PHP file

    <?php
    echo "<pre>"; print_r($_REQUEST); echo "</pre>";
    ?>

Result I am getting

<pre>Array
(
    [country] => Array
        (
            [name] => name
            [code] => 1
        )

    [cars] => Array
        (
            [0] => bmw
            [1] => ferrari
        )

)
</pre>
Sign up to request clarification or add additional context in comments.

Comments

1

JS Fidle Demo

var data = {
    country: {
        name: "name",
        code: 1
    },
    department: {},
    cars: ["bmw", "ferrari"],
    books: []
};

function isEmpty(obj) 
{
    for(var prop in obj) 
    {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

function removeFirstLevelEmptyPropertiesFromJSON(obj)
{
  var isArray = obj instanceof Array;
  for (var k in obj)
  {
      if (obj[k] instanceof Array)  
      {
          if(obj[k].length == 0)
              delete obj[k];
      }
      else
      {
          if(isEmpty(obj[k]))
              delete obj[k];
      }
  }
}
removeFirstLevelEmptyPropertiesFromJSON(data);

var modifiedData = JSON.stringify(data);
alert(modifiedData);

Comments

1

I changed the logic of sending the json data by sending the whole object in one key=value pair:

$.each(data, function (key, value) {
    if ($.isEmptyObject(value)) {
        delete data[key];
    }
});

var posting = $.ajax({
    url: "/do",
    type: "GET",
    traditional: false,
    data: "data=" + JSON.stringify(data),
    dataType: "json"
});

and do parsing on server side.

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.