1

i need to send one array into rails controller via jquery ajax

jquery CODE

$(document).ready(function(){

var counter = 2;
$("#addButton").click(function () {
   var newTextBoxDiv = $(document.createElement('div'))
     .attr("id", 'TextBoxDiv' + counter);

   newTextBoxDiv.after().html('<input type="text" placeholder="Role" name="Role' + 
   counter + 
      '" id="textbox' + counter + '" value="" > <input type="text" 
placeholder="Search" name="search' + counter + 
      '" id="se" value="" >');

newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});



$("#getButton").click(function () {
var fd = new FormData($("#movie-form")[0]); 
var name = document.getElementById("file").files[0].name;
var arr = [];
var msg = '';
for(i=1; i<counter;i++){
  msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); 
      arr[i] = $('#textbox' + i).val();
}
 $.each(arr,function(index, item)
{   
     alert(index);
     alert(item);
   }
);

fd.append( 'file', name);
fd.append( 'file22', name);
$.ajax({
url: '/create',
data: {fd:fd,arr:arr},
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
return false;
});

But it shows the error

Error occurred while parsing request parameters. Contents: REXML::ParseException (The document "[object Object]" does not have a valid root):

2 Answers 2

3

To do an ajax POST request via jquery the data has to be a string.

$.ajax({
    url: "/create",
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify(formData),
    function(data){
        alert(data)
    }
});

Watch out for JSON being undefined in IE6/7. If you need to target those browsers, use this: https://github.com/douglascrockford/JSON-js

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

Comments

0

Could you console.log your array? That'll be much easer and you can inspect the sub elements when you click on it. In FireFox (with FireBug plugin installed) or in Chrome press F12 to open the dev tools and see the console.

I don't think this will work for IE but you can convert a JavaScript object to JSON with JSON.stringify so you can send your msg as JSON:

try:

for(i=1; i<counter;i++){
      arr[i] = $('#textbox' + i).val();
}
msg= JSON.stringify(arr)

The error you're having is from your rails app but you have not posted any code where that error happens.

I'm not sure what rexml does in rails so can't realy help you with that one.

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.