1

Why do my array indices in JavaScript get sent to Ruby as strings? Instead of having scores[0], I access the first element as scores["0"]. I also access my instance vars not as score.candidate_id, but as score["candidate_id"]. How do I make this work?

Code: My JQuery sends scores via AJAX through this function:

$.post("submit.com", {scores: results}, function(data) {console.log(data)}, "json")

where results is an array consisting of

{judge_id: x, category_id: y, candidate_id: z, score: s}

Ruby Back-end (Sinatra and not working)

post '/submit' do

    woot = JSON.parse(params[:scores])

    woot.each do |new_score|
        Score.new({
            score: new_score["score"],
            pageant_id: Pageant.active.id,
            candidate_id: new_score["candidate_id"],
            judge_id: new_score["judge_id"],
            category_id: new_score["category_id"]
            }).save
    end

    params[:scores]["1"].inspect.to_json
end
2
  • Are you sure that results is an array? Commented Sep 20, 2013 at 16:30
  • @ExplosionPills yep, $.isArray returns it as true. Commented Sep 20, 2013 at 16:34

1 Answer 1

1

Try to stringify your parameters before you sending it across. Try using firebug and see how the request is being sent with your current code. This basically happens because jQuery takes those keys in your JSON as names of form elements and it would consider it as though you have an element in your form.

Try sending it like this :

$.ajax({
 type : "POST",
 url :  'submit.com',
 dataType: 'json',
 contentType: 'application/json',
 data : JSON.stringify(results)
 });

In my app i don't use stringify though, but had encountered this issue once and used stringify to pass the data properly.

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

3 Comments

Yes, I used Stringify and it works, I was just thinking if there was a way to make it work without Stringify.
did you try sending as mentioned above without stringify ?
I don't think stringify is actually the essential ingredient here. I just tested multiple methods of POST and arrays within arrays worked BOTH with stringify and without. The defining feature was specifying: contentType: 'application/json'. In other words, Ruby is paying attention to the headers.

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.