-1

I have a very basic app which hooks into the (http://is.gd) API, shortening any user-specified URL. Here's the current code I have to do this (works perfect as a static request):

# app.rb
require "sinatra"
require "open-uri"

def shorten_url(url)
  open("http://is.gd/api.php?longurl=#{url}").read
rescue
  nil
end

get "/" do
  erb :index
end
get "/shorten?" do
  if shorten_url(params[:url])
    flash.now[:success] = "New URL: <strong>#{shorten_url(params[:url])}</strong>"
  else
    flash.now[:error] = "Woops, something went wrong when we tried to convert your URL. Please try again."
  end
end

I am aware that this is a Sinatra app, but I'd be somewhat concerned if users with a Rails background couldn't understand it ;). Here's my index view file...

# index.erb / index.html.erb
<h4>Enter URL</h4>
<form action="/shorten" method="get">
  <input type="text" name="url" placeholder="Enter URL to be shortened...">
  <input type="submit" value="Shorten!">
</form>

So I've got all of that working, now the last thing I want to do is make it so that page doesn't refresh when you submit the form on the index page (AJAX). I know how to do this in jQuery, but is there by any chance a ruby gem that does this? If so, how is it used?

Adam McArthur
  • 950
  • 1
  • 13
  • 27
  • Please note that the flash messages `flash.now` will display on the current request. In my actual static demo, I have `flash.next` followed by a redirect to my index page where the messages are then displayed. I presumed `flash.now` would be used in an AJAX request. – Adam McArthur Sep 16 '13 at 08:18
  • 2
    Read a jquery tutorial. – 7stud Sep 16 '13 at 08:42
  • It can't be done without the bulk of the solution being written in Javascript? – Adam McArthur Sep 16 '13 at 08:46
  • ajax = *a*synchronous *ja*vascript *x*mlhttprequest. Note the middle word. – 7stud Sep 16 '13 at 18:44
  • Was more or less referring to a ruby gem that dealt with the js for me @7stud, but whatever floats your boat. – Adam McArthur Sep 19 '13 at 12:26

1 Answers1

0

You can use JQuery lib. to ajaxify the stuff.

This tutorial tells how to install it http://www.w3schools.com/jquery/jquery_install.asp Then use jQuery.get() function http://api.jquery.com/jQuery.getJSON/ to ajaxify the form submit. Also, note that flash.now does'nt work with ajax requests.

techvineet
  • 5,041
  • 2
  • 30
  • 28