1

I'm wanting to send a post request from my JavaScript code to my show action in Ruby on Rails which contains data that I want to store in an instance variable so I can save it on a form in my view and upload it to my server.

As you can see below, the parameter 'base64' is showing up in my rails logs, but when I try to call @base64 in my view, after grabbing the value in the controller, it's nil.

Any advice is appreciated, thanks!

View

var full_base64 =  "data:image/jpeg;base64," + base64;

                $.ajax({
                    data: 'base64=' + full_base64,
                    type: 'POST',
                    url: "/videos/show/<%=@video.id%>"
                });

Controller

    def show
        @video = Video.find(params[:id])
        if params[:base64].present?
            @base64 = params[:base64]
        end
    end

Routes

post 'videos/show/:id', to: 'videos#show'

Rails server log:

Started POST "/videos/show/1" for 127.0.0.1 at 2020-01-22 12:59:40 -0600
Processing by VideosController#show as */*
Parameters: {"base64"=>"data:image/jpeg;base64,iV...
...
, "id"=>"1"}

Console

>> 

@base64
=> nil
>> 
Seth
  • 119
  • 2
  • 9
  • What do you mean, "in the view"? When/from where are you trying to access it in the console? – Dave Newton Jan 22 '20 at 20:09
  • Since this is AJAX I think we need to know the timeline flow here. You load the view, then send the value via AJAX? Do you then refresh part of the view with the new data? Just because you send it to the controller via AJAX doesn't mean it updates anything on the current page. – Beartech Jan 22 '20 at 21:36
  • So I'm trying to get a JavaScript variable uploaded to my rails server. In my view (html), I have an image in a canvas which I convert to base64. I want to somehow store that in a Ruby variable so I can upload it as an image to my server. I searched online, and the general consensus was to use AJAX, but it's not working for me. And I'm just echoing it in the debug console in the web browser. – Seth Jan 22 '20 at 22:58
  • @Beartech I load the view then I send it via AJAX. I'm not refreshing the view. – Seth Jan 23 '20 at 00:01
  • You are posting via AJAX to a view you are already looking at. If you want to use AJAX you need to follow a certain flow. You need to create a method in your controller that accepts the info, then does something with that info. Then it should send back an AJAX response that updates some part of the page that sent it so you know it worked. – Beartech Jan 23 '20 at 01:12

3 Answers3

1

If I understand correctly you are trying to pass AJAX to the show action in your controller. This is a very GENERALIZED answer as you have failed to include any of your HTML code and it looks like you don't have a button to fire the AJAX. But I'll try to point you in the right direction. You need to do something along the general lines of:

var full_base64 =  "data:image/jpeg;base64," + base64;

            $.ajax({
                data: 'base64=' + full_base64,      
                type: 'POST',
                url: "/videos/my_ajax_upload"
            });

That will send your AJAX call to a controller method I've called my_ajax_upload but you can call it whatever you like. In your controller you would need something like:

def my_ajax_upload
  @video.update(base_64: params[:base64])
  respond_to do |format|
    format.js {render :action => "base_64_response" }
  end
end 

This responds to the initial AJAX call by saving the param you sent to the DB and replying by calling a file called base_64_response.js.erb which might look something like:

$('#pic_upload').html('<%= escape_javascript(render :partial => 'base_64_response') %>');

Which will render the HTML file called base_64_response.html.erb which needs to contain the html code you want to appear in the page that called it.

<div id="pic_upload">
  <%= @base64 =>
</div>

The cycle is load page -> do something to trigger AJAX call to controller method -> process AJAX call with controller method -> render JS file -> JS file replaces div in page with new html

You probably need to read up more on how AJAX works in Rails. This RailsCast might help http://railscasts.com/episodes/136-jquery-ajax-revised?view=asciicast

Beartech
  • 6,173
  • 1
  • 18
  • 41
1

Just FYI - I have also noticed strange things in Rails if you do not explicitly define the content type. In your posted example you are not stating the contentType and it could be parsing nil for that reason. When posting base 64 data you can specify the content type as:

               $.ajax({
                    data: 'base64=' + full_base64,
                    type: 'POST',
                    contentType: 'application/octet-stream'
                    url: "/videos/show/<%=@video.id%>"
                });

and it may change what the controller parses for the body.

How to post an image in base64 encoding via .ajax?

Kai Durai
  • 371
  • 3
  • 10
1

Just use string instead of symbol for hash key

if params["base64"].present?
  @base64 = params["base64"]
end
Lyzard Kyng
  • 1,518
  • 1
  • 9
  • 14