简体   繁体   中英

Sinatra - How to open a bootstrap modal from a redirect

How would I go about automatically opening a modal in the layout.erb after I redirect back from a POST method?

Cart modal opens from button click:

<span class="btn btn-success" data-toggle="modal" data-target="#cart">

Removing an item from the cart:

<form method="post" action="/cart/remove-product"> 
  <input type="hidden" name="id" value="<%= item[:product_id] %>">
  <input type="hidden" name="item_count" value="<%= item[:count] %>"
  <input class="btn btn-danger btn-sm" type="submit" value="x">
</form>

Calls:

class CartController < ApplicationController

post '/remove-product' do
  remove_product_from_cart(request.cookies['cart_id'], params[:id], params[:item_count])
  redirect back

Like @bitsapien alluded to, you can trigger it with ajax — which would require you to submit the form using javascript/ajax. I won't go into how here because there are about half-a-zillion+ questions/answers out there already that can be found with a simple search.

To trigger it, though, you'd have your Sinatra action respond to a request format of xhr . Inside the response (like index.html.erb, index.json.erb, etc.) for the request format of xhr you'd want to return something like $('#my_modal').modal('show');

If you need to redirect the user and for some reason cannot submit the form using ajax, you could — though "hacky" — set a cookie or session with a key (example) of trigger and a value of #my_modal , and then do something like,

<% if session[:trigger] %>
<script><%= "$('#{session[:trigger]}').modal('show');" %></script>
<% session.delete(:trigger) %>
<% end %>

It's not the prettiest, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM