Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to be facing difficulties with getting the success function in my ajax request to display the received text. I suspect that the issue lies with how my controller.rb file is handling the request. Here is what I have so far:

index.html.erb

<%= javascript_include_tag "application" %>

<h1>Welcome to my website#index</h1>

<input class="className" id="idName" type="button" value="Click Me!" id="my_button" remote:true/>

<ul id="ulID">
 <div class = 'wantToChange'>This should change when button is pressed.</div>
</ul>

application.js

$(document).ready(function(){
    $('.className').on('click', function(){
        console.log("inside js click listener");

       $.post('superman', { field1: "hello", field2 : "hello2"}, 
       function(returnedData){
            console.log(returnedData);
       });

    });
});

welcome_controller.rb

class WelcomeController < ApplicationController
  def index
  end

  def superman
    some_parameter = params[:some_parameter]
    #do something with some_parameter and return the results
    render plain: "OK"
  end

end

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  resources :test do
    collection do
      get 'test'
    end
  end

  root 'welcome#index'
end

When I click on the button, an error is generated: POST http://localhost:3000/superman 404 (Not Found) I suspect there may be an issue with how my controller file is configured to receive the 'superman' route. Any assistance on this matter would be greatly appreciated. Thank you.

Answer №1

1=> Welcome.html.erb

<!-- This line is supposed to be in application.html.erb file 
  <%#= javascript_include_tag "application" %>
-->
<h1>Greetings from my website#index</h1>

<input class="className" id="button_to_be_clicked" type="button" value="Click Me!" id="my_button"/>

<ul id="ulID">
 <div class = 'want_to_change'>This text should change upon button click.</div>
</ul>

   <script type="text/javascript">
     $('#button_to_be_clicked').on('click', function(){
      // Sending an AJAX request 
       $.ajax({
         url: "/superman",
         type: "POST",
         data : {
           value1: "hello",
           value2: "hello2"            
         },
         dataType: "script",
      });        
     })
   </script>

2 => routes.rb

Rails.application.routes.draw do
  root 'welcome#index'

  post '/superman', to: 'welcome#superman'

  resources :test do
    collection do
      get 'test'
    end
  end
end

3 => welcome_controller.rb

class WelcomeController < ApplicationController
  def index
  end

  def superman
    value1 = params[:value1]
    value1 = params[:value2]
    render plain: "OK"
  end

end

3 => superman.js.erb

$('.want_to_change').html("Text that will replace the previous one on AJAX request.")

Answer №2

If you want to make an ajax request, the gem remotipart is a great option to use. It's simple to add this gem to your project.

gem 'remotipart', github: 'mshibuya/remotipart', ref: '88d9a7'

After adding the gem, you just need to make some adjustments in the form setup.

<%= form_for @document, :html => { :multipart => true, :id => "create-document-form" }, :remote => true do |document_form| %>
  <%= document_form.file_field :file_upload, class: "custom-file-input" %>
<% end %>

For instance, I have used the above form for submitting a new document via ajax. In the controller, it will be processed accordingly.

def create
  @document = Document.new(document_params)
  respond_to do |format|
    if @document.save
      data = {visible_for_client: @document.visible_for_client, file_name: file_name.to_json, description: @document.description, file_path: file_url}.to_json
      format.js { render :js => "append_document(#{data});" }
    else
      format.json { render json: { errors: @document.errors.full_messages }, status: 422 }
    end
  end
end

Then, I will invoke the JavaScript method from the controller and pass my message data through that method.

function append_document(data){
  console.log("Document created successfully.")
}

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

Having trouble with JSON search not functioning as expected in Select2 4.0?

After numerous hours of effort, I finally managed to successfully load and display the json file, complete with the flag icons using Select2 4.0. The code ended up appearing deceptively simple. However, I am now facing an issue where the search function i ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

Using Java beans to present form data utilizing session

How can I utilize Java Beans and session beans to store user input data and display a preview of the entered details on the next page? I have already created a servlet using JSP, but now I want to incorporate Java Beans to showcase the form data. How shoul ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...

Ways to conceal the picture

Check out the JSfiddle link here for the full code. I'm having trouble with my slider as the last picture keeps collapsing underneath and is not hidden as it should be. I suspect this issue is causing the slider to malfunction. HTML <div class=" ...

Tips for implementing the "Redirect after POST" pattern in ASP.NET [Revised]

I'm new to implementing Redirect After Post in ASP.NET and need guidance. Due to the time-consuming nature of my business objects, I'm unsure about the order and syntax to use. Can someone provide some advice? For instance: User makes a POST ...

What causes directive templates to be fetched from the server at times (resulting in a 304 response), while other times they are retrieved from the browser cache without

I've noticed that when I reload the page, Angular directive templates load in two different ways. The first way is when the browser sends a request to the server and receives a 304 response - everything works fine. However, the second way is puzzlin ...

Is there a way to implement a react component into an HTML file?

I initially created a web page using pure JS, CSS, and Django. Feeling quite ineffective, I decided to try using React JS instead. However, upon making a simple React component, I encountered a problem - I wasn't sure how to incorporate this component ...

Creating mp4 files from a sequence of jpg images using Node.js

My server continuously receives jpg files from a client. The challenge at hand is: how can I create one mp4 file using all of these jpg files? I currently save all the jpg files and then utilize ffmpeg with “filename%3d.jpg” once the client finishes s ...

Integrate PEM certificate into an Http Request with AngularJS/NodeJS

Currently, I am working on an application that requires retrieving data from a REST endpoint within an encrypted network. Accessing this data is only possible by physically being present (which is currently not an option) or using a PEM certificate provide ...

What are the steps for creating a JSON array in JavaScript?

Hello, I'm facing an issue with the following code: javascript var cadena="["; $('.box').each(function(){ var clase=$(this).attr("class"); var id_t=$(this).attr("id"); if(clase=="box ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Working with regular expressions on fieldsets in JavaScript jQuery

I'm facing an issue with a JavaScript regexp and I could really use some assistance. Currently, I have an ajax query result saved in a variable (in this case, a regexp) and I am trying to only match the content within the fieldset tag. Here is a sni ...

Error encounter in JSP is nested within another JSP file, both of which utilize jQuery

Before proceeding, it is important to note that I am in the process of selecting a month using a datepicker and a specific meter (by its serial number). Once this information is selected, a query will be sent to a MySQL database to retrieve data for plotti ...

What is the best way to ensure that two objects collide with one another?

Issue Description I am currently working on implementing collision detection for two objects. The goal is to determine if the objects are intersecting by calculating their bounding boxes with Box3 and using the .intersectsBox() function to obtain a boolea ...

Converting every element in an array into individual hash values?

Query for beginners: I am working with an array called data. It is made up of an array of hashes extracted from a CSV file: [ {:status=>"new", :number=>"215", :subject=>"25", :case=>"First", :attachment=>"alpha, beta"}, {:status=>"old", ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

The mystery of the Accordion Effect: A Next.js/React.js issue where it slides up but refuses to

After implementing a custom accordion using next.js, I encountered an issue where the slide animation worked successfully when moving up and out upon clicking the button. However, when trying to move it back down into the content, it did not animate as exp ...

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...