Unable to append a notification following an XHR request in Rails

When a file is added and redirected correctly, no notice is displayed. However, if xhr is not used, the notice will appear.

application.js

var files = evt.target.files || evt.dataTransfer.files;

// files is a FileList of File objects. List some properties.
for (var i = 0, f; f = files[i]; i++) {
   var xhr = new XMLHttpRequest();
   xhr.open("POST", 'report_drag', false);
   xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
   xhr.setRequestHeader("X_FILENAME", "file." + f.name.split('.').pop());
   xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
   xhr.send(f);
}

controller.rb

def report_drag
    filename = "report/#{DateTime.now.year}-#{DateTime.now.month}/" + "#{Vendor.where(id: current_user.id).first.title}" + "#{File.extname("#{request.headers['HTTP_X_FILENAME']}")}"
    File.open(File.join(filename), "wb") { |f| f.write(request.body.read) }
    redirect_to report_url, notice: "File successfully added."
end

Answer №1

When a user sends a simple request from their browser (by clicking a link, a button, or typing in the address bar), the response replaces the current page and displays instead.

However, if you use XHR (XMLHttpRequest), the browser doesn't change its location or render anything - it expects the JavaScript code to handle the response parsing and interpretation.

If you need to asynchronously communicate with the server and update parts of the page based on responses, check out this tutorial on using Ajax with Ruby on Rails

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

Creating HTML elements with dynamic `routerLink` attributes in Angular 2

I have a model that references itself, as shown below. export class Entity { constructor(public id: number,public name: string,public children: Entity[]) { } } My goal is to create a tree list where each item has a routerlink. To achieve this, I ...

Implementing swipe functionality to Bootstrap carousel

This is the code snippet I am working with: <div class="container"> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="3000"> <!--Indicators--> <ol class="carousel-indicators"> ...

I'm looking for the specific jQuery/JavaScript function that will accomplish this task

let data = [{ name: "abcd", type: "1 kg" }, { name: "efgh", type: "1 cai" }, { name: "ijkl", type: "1 kg" }]; If I have the name, I would like to get the corresponding type. For example, if I call getType('abcd'), it sho ...

The OnClick event is unresponsive when accessing the website on a mobile browser

I have a HTML page where I've included an onclick event in a div tag. Within this event, I'm using location.href = url to open a specific URL. Surprisingly, this works perfectly fine in a web browser but strangely doesn't work in a mobile br ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

What is the best approach to detect multiple .change() events on elements that are dynamically updated through AJAX interactions?

Here is my first question, and I will make sure to follow all the guidelines. In a PHP page, I have two select groups, with the second group initially disabled. The first select group is named "yearlist", while the second select group is named "makelist" ...

Transitioning the existing application from iOS Cordova's UIWebView to WKWebView requires disabling asynchronous JavaScript execution in order to maintain functionality

Previously, in one of our older examples for saving data, we had successfully used the following code in cordova UIWebview without any issues: var filenameID; function getFilenameID() { $.ajax('/jquery/getdata', // request url { success ...

OrbitControls in THREE.JS fail to function properly when a DOM Element is layered on top of the scene

I am attempting to position labels as elements with position:absolute; over a THREEJS scene. The issue arises when the mouse hovers over one of the labels (the red box in the example below), causing the events that trigger OrbitControls to be "halted" by t ...

An error was encountered: object does not possess the function 'tooltip'

I have been attempting to display a tooltip on a textbox using jQuery scripts within a web form that utilizes a Master Page. While everything appears to be working fine when I run my code, I am encountering the above error in the resources folder of the DO ...

Restarting an Angular app is necessary once its HTML has been updated

I've encountered an interesting challenge with an application that combines MVC and Angular2 in a not-so-great way. Basically, on the Index page, there's a partial view loading the Angular app while also including all the necessary JavaScript li ...

Python's Selenium execute script does not support setTimeout function

Hey there! I was attempting to pause the Selenium execution for a few seconds in order to wait for a Modal popup to appear. Unfortunately, using time.sleep(5) did not work with PhantomJS (apparently, PhantomJS does not support sleep function). So, I decide ...

Text-field input experiencing issues with placeholder display

As a beginner in Angular, I may make some mistakes. I created a textField input using a directive in Angular: .directive('textField', function () { return { restrict: 'E', scope: true, require: 'ngModel ...

Unable to maintain active status on Vuejs (PrimeVue) Sidebar component leads to malfunction

I currently have a PrimeVue Sidebar component set up with a dynamic component being passed to it. At the moment, I am only using a single component to test this functionality. <Sidebar v-model:visible="sidebarState" :baseZIndex="1000" ...

Socket.io operates individually with each user

Showing a basic web-chat using socket.io. Node.js code: io.on('connection', function(socket) { // Sends 'hello world' message to all users socket.emit('send:message', { text: 'hello world' }); ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

Uncovering the hidden treasures of checkbox values using jQuery

I've encountered an issue with a form containing checkboxes. Some values are meant to be true by default, so I've hidden them using the following method: <input type=checkbox name="<%= _key %>" checked="checked" style="display:none" /& ...

Guide on redirecting to the login page in angular2 when a process is left incomplete

I am facing an issue with the Popup used for device verification during login. When I click on the login button with valid credentials, a popup opens if the device is not trusted. Once I provide the necessary information and successfully validate, it shoul ...

Scaling Three.js Mesh to fit renderer while maintaining aspect ratio

Currently, I am using the STLLoader plugin from the Github repository of three.js. This is a snippet of my code: this.loadSTL = function(scene, stlFile){ var loader = new THREE.STLLoader(); loader.addEventListener('load', function(g ...

Determining the file extension type of an uploaded file using JavaScript

In my new file upload system, users have the option to upload both images and videos. After uploading a file, I provide a preview of the uploaded content. Desired Outcome: My goal is to display only ONE preview based on the type of file (image or video). ...

Combining Laravel and vue.js for seamless file uploading functionality

Successfully uploading files using vue.js 1.0 with a POST request looks like: store () { this.storingMessage = true; var form = new FormData(); form.append('subject', this.message.subject); form.ap ...