I am working on a rails app and I want to create a dynamical amount of variables to pass to my controller via an AJAX request. That is, I want to create 3 variables if there are only 3 objects and 5 variables if there are 5 objects.
In my javascript file, I’ve already managed to create a dynamic amount of variables.
var count = parseInt("#{@matches.count}");
while(count>0){
eval("result_" + count + "= $('input:radio[name=result_" + count + "]:checked').val()");
count -= 1;
}
This creates result_1, result_2, result_3, etc.
The AJAX request I have so far is static in that it always has to have 5 results. I want this to be dynamic.
$.ajax({
type: 'GET',
url: '/mt_results/create',
dataType: 'json',
data: {
'result_1' : { matched_id: "#{@matches.first.id}", result: result_1 },
'result_2' : { matched_id: "#{@matches.second.id}", result: result_2 },
'result_3' : { matched_id: "#{@matches.third.id}", result: result_3 },
'result_4' : { matched_id: "#{@matches.fourth.id}", result: result_4 },
'result_5' : { matched_id: "#{@matches.fifth.id}", result: result_5 }
},
success: function(e){
console.log("AWWWWWWW YEAH!!");
}
});
Is the best way to approach this to dynamically create the JSON object (similar to how I created results_#) and assign it to a variable (let’s call it data_var). Then, I can just pass data_var like below:
data: data_var
Any tip or feedback on how I can improve my code would be greatly appreciated.
In my opinion, when you write JS, you should not use inline ruby unless absolutely necessary. Most of the times, it’s a sign of bad design and produces code that is tightly coupled to your server-side logic.
It’s better to store the data you need in your tag attributes – or use those that already exist.
in your case, you could do :
(btw, you should not use radio buttons when you allow multiple choices – use checkboxes)
if you really need to add more data, you can do it the html5 way by adding this to the options :
which would add these attributes to the tag :
Now – you want to analyze these boxes and send an ajax request to whatever. Why even bothering analysis ? Rails gives you a simple way to handle remote forms. Just wrap your boxes in a remote form, submit it on click, and there you go – it even degrades gracefully !
If you have something more difficult to perform (with data-attributes…), crafting yourself the ajax call data is always possible :