The challenge of verifying CSRF token authenticity persists when uploading gifs using Carrierwave in AJAX requests

Uploading normal jpeg images and pngs through AJAX in Rails does not throw any errors. However, when attempting to upload a gif (which is whitelisted), the user gets redirected back to the home page. The issue seems to be with the absence of a csrf_token during the form submission. Is there a way to include a csrf_token in the form when using create.js.erb?

Server Development Log

Started POST "/posts" for 127.0.0.1 at 2019-02-24 19:39:51 -0500
Processing by PostsController#create as HTML
  Parameters: {"utf8"=>"✓", "post"=>{"body_text"=>"Testing the gif again!", "photo_cache"=>""}, "commit"=>"Post"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 51], ["LIMIT", 1]]
Can't verify CSRF token authenticity.
   (1.0ms)  BEGIN
   (0.0ms)  COMMIT
Completed 401 Unauthorized in 110ms (ActiveRecord: 2.0ms)


Started GET "/login" for 127.0.0.1 at 2019-02-24 19:39:53 -0500
Processing by Devise::SessionsController#new as HTML
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 51], ["LIMIT", 1]]
Redirected to https://127.0.0.1/
Filter chain halted as :require_no_authentication rendered or redirected
Completed 302 Found in 5ms (ActiveRecord: 1.0ms)


Started GET "/" for 127.0.0.1 at 2019-02-24 19:39:55 -0500
Processing by HomeController#index as HTML

posts_form.html.erb

<%= simple_form_for(@post, multipart: true, remote: true) do |f| %>

  <div class="row">
    <div class="col">
      <div class="post-textarea">
          <%= f.input :body_text, as: :text, class: 'form-control post-placeholder', label: false, placeholder: 'Add a post to share with others', style: "overflow: hidden; resize: none;" %>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-5">
      <%= f.button :submit, 'Post', class: 'form-control submit-button bttn-gradient bttn-md bttn-royal', :data => {:disable_with => 'Wait...a min'} %>
    </div>
    <div class="col-md-5">
       <label class="bttn-minimal bttn-md bttn-royal">
        Add Photo
        <span style="display:none;">
            <%= f.input :photo, as: :file, label: false, input_html: {accept: 'image/*'} %>
            </span>
      </label>
      <% if f.object.photo? %>
        <%= image_tag f.object.photo.url(:feed_preview), class: 'img-responsive img-thumbnail' %>
      <% end %>
      <%= f.hidden_field :photo_cache %>
      <div class="post-preview-container">
        <img id="img_prev" width="100" height="100" src="#" alt="preview" class="img-thumbnail d-none"/> <br/>
        <a href="#" id="cancel_img_btn" class="d-none" onclick="return !(document.getElementById('photo').innerHTML=document.getElementById('photo').innerHTML);">Cancel
      Upload</a>
      </div>
    </div>
  </div>
<% end %>

create.js.erb

$("#container_posts").prepend("<%= j render partial: "posts/#{@post.post_type}", locals: {post: @post } %>");
$("#post_<%= @post.id %>").hide().fadeIn(1000);
$("#no-posts").hide().fadeOut();
$("#body_text").val("");
$("#img_prev").hide().fadeOut();
$("#cancel_img_btn").hide().fadeOut();

Answer №1

Give it a shot and see if this approach yields results.

<%= Using the simple_form_for method, try passing in @post with options such as multipart, remote, and authenticity_token set to true like below: %>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm experiencing issues with my PHP code not properly receiving the data from the $.ajax function

After extensive searching and researching various similar queries, I am still unable to find a solution to my problem. The issue at hand is that I aim to input data into a MySQL database using the $.ajax function. To achieve this, I have set up a form (f ...

What is the best way to transfer GitHub OAuth information to a client?

I am in the process of implementing Github authorization and then sending received JSON data to the client. After doing some research, I came across a helpful tutorial at The tutorial suggests following this path: "/" -> "/login" -> "/redirect" -&g ...

Utilizing MongoDB in Node.js Environment

I am currently facing an issue with connecting to a larger database through node. In the past, I have successfully connected to smaller databases using a Mongo URL in this format: mongodb://[username]:[password]@db1-a0.example.net:27017/[DB-Name] However ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

What could be causing the unexpected behavior of TypeScript in Visual Studio Code?

VSCode is showing errors, but everything is functioning properly. Here are some of the errors: Type expected. [ { "resource": "/C:/Users/Dell/Desktop/vite-project/src/App.tsx", "owner": "typescript", "code": "1110", "se ...

Save log discrepancies to a document

Upon completing my website for graduation, there is still one important feature I want to add. I would like to implement a script that sends the name of the website where it is installed, as well as any error messages, to my website. For instance: The fol ...

Obtaining a null value for the city dropdown when inserting a record into the table

In my form, I have 2 dropdown controls for State and City. I am filling the City dropdown using AJAX jQuery by calling a Web method on the server side. However, on the submit event, I am running into an issue where the selected value is not being retrieved ...

IE9 does not consider JavaScript variable as undefined

Hello, I came across this JS code written by someone else: function somename(f) var procName = ""; var procParams = new Array(); var parseEl = ""; var parseEls = new Array(); var parseInd = 0; var procParamsInd = 0; var IsVal ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Constantly defining the fill color in an SVG with AngularJS

In the front end, I am using a constant as a select box that contains an SVG element. The objective is to insert the SVG into the DOM and have it functional. (function () { 'use strict'; angular.module('app.constants', []) ...

Why does console.log in JavaScript exhibit different behaviors as evidenced by the code?

Exploring the behavior of console.log(obj) compared to console.log("obj"+"\n"+obj) in the code snippet below reveals two distinct output outcomes. const obj = new Object() obj.first = 'John' obj.last = 'Doe' obj.alive = true ob ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

Chrome debugging tool does not refresh page source

This issue has been lingering for quite some time and despite similar questions, I have not come across a satisfactory solution. The problem lies in the fact that the SOURCE used to step through the code does not refresh with every page load. Disabling the ...

What is the best way to generate a Google chart inside a newly added element using jQuery?

Currently, I am in the process of constructing a webpage that showcases a Google chart for all active sports games happening on that particular day. A data feed will provide information on the number of active games (as shown below, with 3 ongoing games). ...

Purging AJAX responses upon completion of loading

I am currently implementing an AJAX request to display search suggestions dynamically: $(".smart-suggestions").load('id-get-data.php?searchword=' + self.value); As the search suggestions populate in a 'div' based on user input, I am i ...

Create a single HTML page with multiple images displayed

I've come up with a clever solution to display images in one HTML file and show them full-sized in another. Instead of creating multiple HTML files, I want to achieve this with just one. By using JavaScript, when a user clicks on an image in the first ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

Utilizing the $divide feature in MongoDB aggregation

As a newcomer to javascript, I am seeking assistance with calculating the average number of sales (averageSales = totalSales/ numOrders). I am encountering some challenges in this process and would highly appreciate any help or guidance provided. ...

Are you searching for the origin of a dynamic dropdown widget or database?

Currently, I am browsing through and I have a query regarding accessing all available classes/options for the courses in a semester. There is a class locator on the top left of the page with a dynamic drop-down menu. Can anyone suggest how I can access ...

Is there a way to decrease the speed of a range slider?

Recently, I created a range slider using HTML, CSS, and JS to complement my Lua Nui. It's been working smoothly for the most part, but I've noticed an issue when sliding too quickly on the slider. As I slide it to the left, certain values fluctua ...