0

I have a form at http://localhost:3000/ with data-remote='true', the purpose of which is to upload an image:

<form class="carousel" enctype="multipart/form-data" action="/image_carousels/1" accept-charset="UTF-8" data-remote="true" method="post">
  <input name="utf8" type="hidden" value="✓">
  <input type="hidden" name="_method" value="patch"><input type="hidden" name="authenticity_token" value="...">
  <input type="file" name="image_carousel[image]">
  <button name="button" type="submit">Submit Image</button>
</form>

The controller behaves as if the request were for html. So if I make a view in image_carousels/update.html.erb as follows:

<p>Image Uploaded!</p>

This gets displayed at http://localhost:3000/image_carousels/1.

I'm confused as to why an html response is being expected and even displayed on a new page when I have set data-remote='true'.

Why is it behaving this way and, without changing the page, how do I:

  1. Display a simple alert to the user to say the image has been uploaded
  2. Return some json with {message: "Image uploaded successfully"} and then display the message to the user (for example's sake)
  3. Return some html to be displayed after the form

(Some of these are just to improve my understanding)

Vorpulus Lyphane
  • 660
  • 6
  • 19
  • Answer might be something to do with not being able to upload a file asynchronously. See https://stackoverflow.com/questions/24681837/async-file-uploads-with-rails-4 – Vorpulus Lyphane Sep 11 '19 at 13:57

1 Answers1

0

Use form_tag and give remote: true example <%= form_tag("/image_carousels/1", method: 'post', remote: true ) do %>

In controller make response like below

respond_to do |format|
 format.js 
end

create file in views upload.js.erb and write a alert in this file. Just try this and tell me if you have any query

kishore cheruku
  • 511
  • 2
  • 11