3

I am sending an array in AJAX request:

$.ajax(
    {
        type: "POST",
        url: "http://192.168.0.15/calc",
        data: {
            "phone": phone,
            "points": [
                { "lat": 59.15234, "lon": 30.99 },
                { "lat": 59.15244, "lon": 30.99 },
                { "lat": 59.15254, "lon": 30.99 }
            ],
            "start_at": 1407249093,
            "certificate": "849840487484"
        },
        success: function(data) {
            alert('success');
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.statusCode());
            console.log(textStatus);
            console.log(errorThrown);
        }
    }
);

Then inspect points:

params[:points].inspect

and see a hash:

{
  "0"=>{"lat"=>"59.15234", "lon"=>"30.99"},
  "1"=>{"lat"=>"59.15244", "lon"=>"30.99"},
  "2"=>{"lat"=>"59.15254", "lon"=>"30.99"}
}

How to get an array instead of hash (preferably initially, without having to convert the hash to array)?

Paul
  • 25,812
  • 38
  • 124
  • 247
  • 1
    possible duplicate of [Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys)](http://stackoverflow.com/questions/6410810/rails-not-decoding-json-from-jquery-correctly-array-becoming-a-hash-with-intege) – jvnill Aug 08 '14 at 11:08

2 Answers2

1

solution here

Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys)

simply you need to add the content type and set it to contentType: 'application/json'

Community
  • 1
  • 1
Moustafa Sallam
  • 1,110
  • 1
  • 9
  • 17
  • Unfortunately the solution pointed out there causes the jQ to send an OPTIONS request. I didn't even know that this HTTP method exists. Response is 404. – Paul Aug 08 '14 at 11:52
  • P.S. It was because of same domain policy. After putting the ths form into web application everything is working fine. – Paul Aug 08 '14 at 13:22
0

If you can then do:

"points": [
    '{ "lat": 59.15234, "lon": 30.99 }',
    '{ "lat": 59.15244, "lon": 30.99 }',
    '{ "lat": 59.15254, "lon": 30.99 }'
]

Now this will be considered as array of strings and when parsing you can convert it to hash to parse.

Tell me if this solves your issue.

EDIT

$.ajax({
  ..
  ..
  dataType: 'json',
  contentType: 'application/json',
  data : JSON.stringify({"points": [
     { "lat": 59.15234, "lon": 30.99 },
     { "lat": 59.15244, "lon": 30.99 },
     { "lat": 59.15254, "lon": 30.99 }]
  })
});
Abdul Baig
  • 3,683
  • 3
  • 21
  • 48