leon
leon

Reputation: 441

How to send JSON array together with data from form in Rails?

I have view with form contains a few fields and Google maps with tool to drop markers. I want to attach to the request markers coordinates stored as JavaScript JSON array. I would send after filling out all fields and select markers all data by clicking only send button. Form converted by jQuery $(this).serialize() doesn't accept by Rails. Illustrative material:

JavaScript:

$('form').submit(function () {
    var url = $(this).attr('action');
    var data = { post: JSON.stringify(markersArray) };
    // var data = $(this).serialize();

    $.post(url, data, function(result) {
        //result
    });
    return false;
});

Rails controller:

def create
  received_data = params[:post]

  markersArray = ActiveSupport::JSON.decode(received_data)

  #only JSON
  @post = Post.new(markersArray)

  #normal approach only form
  #@post = Post.new(received_data)
  @post.save
end

EDIT

Received JSON:

Parameters: {"post"=>"{\"markers\":[[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003],[52.40393,16.92406]]}"}

Received form:

Parameters: {
    "utf8"=>"✓", 
    "authenticity_token"=>"nehoT1fnza/ZW4XB4v27uZsfFjjOu/ucIhzMmMKgWPo=", 
    "post"=>{
         "title"=>"test", 
         "description"=>"fewfewfew"}, 
    "commit"=>"Save"}

Upvotes: 0

Views: 4798

Answers (1)

topek
topek

Reputation: 18979

You could temporarily add a hidden field and remove it after serialization:

$('form').submit(function () {
    var url = $(this).attr('action');
    var tempField = $('<input type="hidden" name="post" />').val(JSON.stringify(markersArray)).appendTo(this);
    var data = $(this).serialize();
    tempField.remove();

    $.post(url, data, function(result) {
        //result
    });
    return false;
});

or you could send an object from the deserialized data, enhaced with your post data

$('form').submit(function () {
    var url = $(this).attr('action');
    var data = jQuery.parseJson($(this).serialize());
    data.post =  JSON.stringify(markersArray) 


    $.post(url, data, function(result) {
        //result
    });
    return false;
});

Upvotes: 1

Related Questions