Skip to content

acconrad/fetch-rails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 

Repository files navigation

fetch-rails

Use GitHub's fetch library with Ruby on Rails. Based heavily on this wrapper to encapsulate some of the callback handling of HTTP status codes.

Installation

  1. Make sure you have the fetch library added to your app.js manifest file.
  2. Ensure your root layout file (usually called app/views/layouts/application.html.erb) has <%= csrf_meta_tags %> within the <head> tag.
  3. Copy the fetch-rails.js to your /vendor/assets/javascripts/ folder.
  4. Add //= require fetch-rails directly below where you have added the fetch library to your app.js manifest.

Usage

HTML GET request

Fetch.html( '/api/web/get-html' )
  .then( function( response ){
    document.body.innerHTML = response.data;
  });

JSON GET request

// endpoint returns { name: 'Adam', age: 30 }
Fetch.json( '/api/web/get-json' )
  .then( function( data ){
    this.name = data.name;
    this.age = data.age;
  });

Text GET request

Fetch.text( '/api/web/get-text' )
  .then( function( text ){
    document.querySelector( '.item' ).innerText = text;
  });

Form POST request

Fetch.post( '/api/web/submit-form', 'form.my-form' )
  .then( function( response ){
    document.querySelector( '.alert' ).innerText = 'Form submitted!';
  }).catch( function( error ){
    document.querySelector( '.alert' ).innerText = error;
  });

With file uploads

Fetch.post( '/api/web/submit-form', 'form.my-form', 'input.file-uploader' )
  .then( function( response ){
    document.querySelector( '.alert' ).innerText = 'File uploaded!';
  }).catch( function( error ){
    document.querySelector( '.alert' ).innerText = error;
  });

JSON POST request

Fetch.postJSON( '/api/web/post-json', { name: 'Adam', age: 30 } )
  .then( function( response ){
    document.querySelector( '.alert' ).innerText = 'JSON submitted!';
  }).catch( function( error ){
    document.querySelector( '.alert' ).innerText = error;
  });

Support

Rails

  • Rails 4.0+

Browsers

  • Chrome latest
  • Safari latest
  • Firefox latest
  • Opera latest
  • IE 9+
  • Safari mobile latest
  • Chrome mobile latest

About

Use GitHub's fetch library with Ruby on Rails.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published