Sinatra's 'post' route failing to render template

My project involves a basic Ruby app built on Sinatra. I am currently working on implementing a feature where a form can dynamically update the page based on user input. For instance, when a user enters their name in a form field and hits "go," the page should display a personalized greeting like "Welcome {name}" without requiring a page refresh.

Here is the relevant code that I have functioning:

In my app.rb file:

get '/examples' do
    erb :example
end

post '/examples' do
    post = params[:post]
    @name = post['name']

    puts "HERE"
    erb :example

Snippet from my example.erb file (showing only the form):

<% if @name then %>
    <%= @name %>
<% end %>


<form id="myForm" action="/examples" method="post">
  Name: <input type="text" name="post[name]" />
  <input type="submit" value="Submit Name" />
</form>

Additionally, here is the JavaScript file snippet:

// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
    alert("Thank you for your comment!");
});

The issue arises after the execution of the post route in the app.rb file; despite seeing "HERE" printed in the terminal and receiving an alert, the page fails to update. I attempted applying a redirect call in the post route as well, but it did not resolve the problem. Any suggestions or solutions?

Answer №1

It seems like you are using the jQuery Form Plugin. The issue might be that jQuery is handling the post request, preventing the page from reloading and causing <%= @name %> not to be evaluated as it wasn't available initially.

To resolve this, consider utilizing jQuery Form's options to specify a target HTML element where the response will be displayed (check out an example here).

I suggest creating a separate view for the response to avoid returning unnecessary content along with it in your example.erb view.

Here is an updated example.erb:

<div id="output1">
</div>

<form id="myForm" action="/examples" method="post">
  Name: <input type="text" name="post[name]" />
  <input type="submit" value="Submit Name" />
</form>

<script> 
  $(document).ready(function() { 

    var options = { 
      target: '#output1',   // defining target element(s) for server response update 
    }; 

    // attaching 'myForm' and providing a basic callback function 
    $('#myForm').ajaxForm(options, function() { 
      alert("Thank you for your comment!"); 
    }); 
  }); 
</script>

Updated web.rb file:

get '/examples' do
    erb :example
end

post '/examples' do    
  post = params[:post]
  @name = post['name']

  puts "HERE "

  erb :response
end

New response.erb view:

<% if @name then %>
  <%= @name %>
<% end %>

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

Utilize axios to retrieve data and pass it as props to a component

I am new to react and struggling with a basic issue. I need help passing an array of values from an external service as a prop to another component. Approach render() { let todolist="default"; axios.get('http://localhost:8888/todoitems').t ...

React Material UI unselect

I have been exploring a MUI select field implementation using this example as a guide. While I was able to make the code work, there are a few issues that I encountered. One of them is the inability to deselect a value once it has been selected. Additional ...

Accessing Flipkart API using CORS: A step-by-step guide

Trying to retrieve data from the following URL using a jQuery ajax call: Ajax request $.ajax({ type:"GET", url: 'https://affiliate-api.flipkart.net/affiliate/report/orders/detail/xml?startDate=2015-05-01&amp;endDate=2015-05-30&amp;st ...

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

"Selecting an option triggers a change in the dropdown

I am working with 2 select menus: <select name="nama_paket"> <?php do { ?> <option value="<?php echo $row_qpaket['nama_paket']?>"><?php echo $row_qpaket['nama_paket']?></option> <?php } while ( ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

TypeScript is not compatible with the intended ECMAScript version

Out of the blue, it seems like my VS17 has started transpiling my TypeScript to ECMAScript 6, but now VS is not accepting it and throwing a bunch of SCRIPT1002 and SCRIPT1006 errors suddenly: "JavaScript critical error at line 3, column 5 in http://localho ...

Create an SVG timeline representation

I am attempting to create a circular timeline using SVG. I am utilizing fullpage js for this purpose. I have successfully implemented a blue line that progresses around the circle as the user scrolls. Now, I am looking to make my anchors dash array visible ...

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Saving a dynamic form to the database and editing it later

I have developed a dynamic form builder using jQuery UI that allows users to drag form inputs anywhere on the screen and generate a report. Now, I am trying to figure out the best approach for saving this layout to a SQL database. How can I save the struct ...

Examining various variables following the identical set of "guidelines"

Currently, I am faced with the task of building an array of objects. While I can manually create these objects one by one, my goal is to streamline the process by iterating through certain variables and dynamically inserting them into the designated spots ...

What is the method to pass raw strings via a jQuery POST request?

Attempting to use jQuery.ajax() to POST a raw string. For example: contact_list=352345 Here's the code snippet: $.ajax({ beforeSend: function(xhr){ xhr.setRequestHeader('Content-Type', header); } }, ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Disabling paste functionality in a textfield can be achieved by adding a

I need to create two textfields, one for entering an email and the other for confirming the email. I want to prevent the user from pasting anything into the confirm textfield using ctrl+v or the mouse in a Struts 2 application. Most examples I've com ...

Challenges of implementing an infinite scroll feature using PHP, jQuery, MySQL, and AJAX

Hey there! I'm in the process of developing this website: It's almost complete, but I'm facing a challenge with the "Coleccion" section. In this section, users select a specific type of bag, and only 20 bags are initially loaded from a MySQ ...

Easiest Way to Implement jQuery AJAX

Is there a way to continuously update the user's status as ACTIVE on the server every minute without requiring a response? setInterval(function() { $(document).load('path/to/keep-user-active.php'); }, 60000); The PHP script will handle ...

Button click triggers CSS animation

Check out the interactive demo $(document).ready(function(){ $('#btn-animate').click(function(){ animate(); }); $('#btn-remove').click(function(){ $('.to-animate').removeClass('animate'); }); func ...

Avoid clicking on the HTML element based on the variable's current value

Within my component, I have a clickable div that triggers a function called todo when the div is clicked: <div @click="todo()"></div> In addition, there is a global variable in this component named price. I am looking to make the af ...