5

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)?

1

2 Answers 2

2

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'

Sign up to request clarification or add additional context in comments.

2 Comments

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.
P.S. It was because of same domain policy. After putting the ths form into web application everything is working fine.
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 }]
  })
});

1 Comment

This seems to look like a workaround rather than real solution.

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.