Skip to content

Instantly share code, notes, and snippets.

@jennli
Last active March 3, 2016 00:54
Show Gist options
  • Save jennli/4cc85f4964405941d77e to your computer and use it in GitHub Desktop.
Save jennli/4cc85f4964405941d77e to your computer and use it in GitHub Desktop.

Asynchronous Javascript and XML

how to make something with ajax?

  • form
<%= form_for [@question, @answer], remote: true do |f| %>
<div>
  <%= f.text_area :body %>
</div>
<%= f.submit %>
<% end %>
  • controller: create
def create
    @question = Question.find params[:question_id]
    answer_params = params.require(:answer).permit(:body)
    @answer = Answer.new answer_params
    @answer.question = @question
    @answer.user = current_user
    respond_to do |format|
      if @answer.save
        AnswersMailer.notify_question_owner(@answer).deliver_later
        format.html{
          redirect_to question_path(@question), notice: "Answer created!"
        }
        # format.js {render js: "alert('answer created, refresh page')"}
        format.js { render :create_success }
      else
        format.html{render "/questions/show"}
        format.js {render js: "alert('error happend');"}
      end
    end
  end
  • controller: index
def index
    @products = Product.order("price DESC")
    respond_to do |format|
      format.html {render}
      format.json {render jason: @products.to_json}
      format.xml {render json: @products.to_xml}
    end
  end
  • view: create a file called create_sucess.js.erb
$('.answers').prepend('<div><%= @answer.body %>}</div>')
  • another way to write this view is to create a answer.html.erb file
<li><%= answer.body %> <em>created_by: <%= answer.user_full_name %></em>
  <% if can? :destroy, answer %>
  <%= link_to "Delete", question_answer_path(@question, answer),
  method: :delete,
  data: {confirm: "Are you sure?"} %></li>
  <% end %>
  • and in the show page:
<div class="answers">
  <ul>
    <% @question.answers.each do |ans| %>
    <%= render "/answers/answer", answer: ans %>
    <% end %>
  </ul>
</div>
  • in create_sucess.js.erb
<%# js is a rails helper method to escape the javscript%> 
<%# so it doesn't break because of the quotes and new lines characer %>
$('.answers').prepend("<%=j render 'answer', answer:@answer %>")

json

  • get
$.get('localhost:3000/messages?limit=10')
  $.get('/messages', function (msg) {
    for(var i = 0; i < msg.length; ++i){
      console.log(msg[i].body);
    }
  });
  • post
$.post('/messages', {body: "Jen Li"})
  • update
    $.ajax({
      url: "/messages/33303",
      method: "PATCH",
      error: function() {
        alert("try again!");
      },
      success: function(){
      alert("updated");
      },
      data: {body: "Jen Li Updated"}
      
    });

json with rails

gem 'rack-cors', :require => 'rack/cors'
  • in application.rb, put the following config for rack cors
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment