简体   繁体   中英

Can't get Json data to Ajax in Rails 5

Hi I'm trying to understand and implement Rails action controller with Ajax. My question is why I can't get Json data and display it to console.log in my Ajax function. I put my ajax function in application.js file. My ajax get method works fine but post method seems doesn't work. In article index page when you click new article it will render partial form and ajax will communicate with create action in controller to append data to index page. But I can't parse Json data to Ajax post. Here are my code files: Updated image enter image description here When I click create only json data in network tab show. Alert and console.log don't show anything.

application.js

$(function (){
var $article_table = $('#article_table');
$.ajax({
    type: 'GET',
    dataType: 'json',
    url: '/articles',
    success: function(articles){
        $.each(articles, function(i, article) {
            $article_table.append('<tr><td>'+article.name+'</td></tr>')
        });
    }
});
$('#form_article').submit(function(){
    //var name = $('#article_name').val();
    var name = JSON.parse(xhr.responseText);
    $.ajax({
        type: 'POST',
        url: '/articles',
        dataType: 'json',
        data: name,
        success: function(data){
            //alert(data.id);
            console.log('success',data);
            //debugger;
        },
        error: function(){

        }
    });
});

articles_controller.rb => in create controller I render article to json

   class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.all
  end

  def show
  end

  # GET /articles/new
  def new
    @article = Article.new
  end

  # GET /articles/1/edit
  def edit
  end

  # POST /articles
  # POST /articles.json
  def create
    @article = Article.new(article_params)

    #respond_to do |format|
      if @article.save
        #format.html { redirect_to @article, notice: 'Article was successfully created.' }
        #format.json { render :show, status: :created, location: @article }
        #format.html
        #format.json { render json: @article, status: :ok}
        render json: @article, status: :ok
      else
        #format.html { render :new }
        #format.html
        render json: @article.errors, status: :unprocessable_entity
        #format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    #end
  end

_form.html.erb:

    <%= form_with(model: @article, remote: true , id: :form_article) do |form| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>

      <ul>
      <% @article.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :article_name %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

index.html.erb:

<p id="notice"><%= notice %></p>

<h1>Articles</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody id="article_table">

  </tbody>
</table>

<br>

<%= link_to 'New Article', new_article_path, id: :new_article_link, remote: true %>

new.js.erb:

 $('#new_article_link').hide().after("<%= j render 'form' %>");

You need to pass the data like

data: {article: {name: name}}

On the jQuery/AJAX part see the below

$('#form_article').submit(function(){
    // Declare a variable for get data from input field
    var name = $('#article_name').val();
    $.ajax({
        type: 'POST',
        url: '/articles',
        dataType: 'json',
        data: {article: {name: name}},
        success: function(data){
            //alert(data.id);
            //console.log('success', data);
            console.log(JSON.stringify(data));
            //debugger;
        },
        error: function(){
            alert("Error");
        }
    });
});

Hope it helps

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