简体   繁体   中英

How to pass a JavaScript var into a Rails Controller

I'm looking to pass a JavaScript variable into a Rails Controller . The interesting part is that the variable is generated inside Canman , and I cannot use it (yet) outside of it.

This is probably just JavaScript and not necessarily related with Canman. But I'm just not sure what it is happening here.

The approach I'm following (but completely open if there is a better way) is to populate a hidden field with jQuery, just to access the data via params from the controller.

If possible (and if this is a good practice) I will like to avoid the form, and just call some JavaScript on click and then pass that variable to the controller.


View

= form_for @post do |form|
  = form.hidden_field :base64
  = form.submit


JavaScript

$('form').submit(function(event){

  Caman('#canvas', img, function() {
    var imageBase64 = this.toBase64();
    alert(imageBase64); // works fine
    $('#post_base64').val(imageBase64);
  });

  alert(imageBase64); // nothing
});


PostsController

def update
  @post = Post.find(params[:id])
  raise '¯\_(ツ)_/¯'
  ...
end


post_params

=> {"base64"=>""}

Also, I read that an option could be to make an AJAX request. However, I'm not sure how to proceed with that, yet.

At some point, I tried with a text_area instead of a hidden_field. The text_area got populated with the right data. However, params never got the data. If I got back via the browser button, the data was in the text_area, and clicking on submit one more time, populates the params as expected.

在此处输入图片说明

Thanks in advance!

Short answer: Ajax .

The goal was to send the value of a variable (a base64 image) to my rails controller, and once there, keep going just with Ruby.

At the end, I created a simple Ajax function to send data from my client (Image from browser) to my server (Rails Controller) via params

save_canvas.js

$(document).on('click', '.save_canvas', function() {
  event.preventDefault()
  var base64Data = canvas.toDataURL('png')

  $.ajax({
    type:    "POST",
    url:     "http://localhost:3000/pictures/",
    data:    { image: base64Data },
    success: function(post){ console.log('success') },
    error:   function(post){ console.log(this) }
  })
})

pictures_controller.rb

  def create
    @picture = Picture.new(image: params[:image])
    @picture.save
    redirect_to @picture
  end

I got support to achieve this here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM