---
# System prepended metadata

title: '[Ruby On Rails]簡易ajax POST範例(使用jQuery)'
tags: [Ruby On Rails]

---

# [Ruby On Rails]簡易ajax POST範例(使用jQuery)

###### tags: `Ruby On Rails`

>記得先引用jquery

## 產生controller

terminal
```terminal
rails g controller users
```
## 產生model

terminal
```terminal
rails g model User name:string mail:string phone:string
```
## 建立資料表

terminal
(rails 4)
```terminal
rake db:migrate
```

(rails 5)
```terminal
rails db:migrate
```

## Route

routes
```rust
  get 'users/new'
  post 'users/create'

```

## View

views/users/new.html.erb
```rust=
<form>
  name<input type="text" id="name"><br>
  email<input type="text" id="mail"><br>
  phone<input type="text" id="phone"><br>

  <button onclick="createNewUser()">submit</button>


</form>

<script>

  function createNewUser(){
    
    //需加上這句以避免form進行自動提交
    event.preventDefault();
    
    $.ajax({
      
      url: "/users/create",
      type: "POST",
      contentType: 'application/json',
      dataType: "json",
      data:JSON.stringify({
        user:{
          "name":$("#name").val(),
          "mail":$("#mail").val(),
          "phone":$("#phone").val(),
        }
     }),
      success: function(data) {
        console.log("success!!");
        console.log(data);
      },
      
      error: function(err) {
        console.log("ERROR!!!");
        console.log(err.status);
        console.log(err);
      }
    });
  }

</script>

```
## Controller

controllers/users_controller
```ruby=
class UsersController < ApplicationController
  def create

    @user = User.new(user_params)

    if @user.save
      render json: {"result": "success"}
    else
      render json: {"result": "fail"}
    end

  end

  private
  def user_params
    params.require(:user).permit(:name,:mail,:phone)
  end
end
```

>這邊要注意的是,
>因為view的js ajax有加上dataType: "json",
>所以,若controller回傳的資料不是json格式的話,
>會被jq ajax判定為error而落到js的error block內,
>導致明明有成功post卻在console印出"ERROR!!!"的情形發生.
>
>(參考以下連結說明:)
>https://stackoverflow.com/questions/6186770/ajax-request-returns-200-ok-but-an-error-event-is-fired-instead-of-success

