Hi, I'm using (REACT and Ruby on Rails) together and ajax
and scaffold
together to make a POST
, PUT
, DESTROY
, GET
but at the time of doing the POST
simply does not do anything, this is my code:
handleClick() {
var name = this.refs.name.value;
var description = this.refs.description.value;
$.ajax({
url: '/items',
type: 'POST',
data: { item: { name: name, description: description } },
success: (item) => {
this.props.handleSubmit(item);
}
});
}
Button:
<button onClick={this.handleClick}>Submit</button>
Controller:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
# GET /items
# GET /items.json
def index
@items = Item.all
end
# GET /items/1
# GET /items/1.json
def show
end
# GET /items/new
def new
@item = Item.new
end
# GET /items/1/edit
def edit
end
# POST /items
# POST /items.json
def create
@item = Item.new(item_params)
respond_to do |format|
if @item.save
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: @item }
else
format.html { render :new }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /items/1
# PATCH/PUT /items/1.json
def update
respond_to do |format|
if @item.update(item_params)
format.html { redirect_to @item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: @item }
else
format.html { render :edit }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /items/1
# DELETE /items/1.json
def destroy
@item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
@item = Item.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def item_params
params.require(:item).permit(:name, :description)
end
end
The detail is that when you press submit
you just reload the page and do not add anything. in console it does not show any error, and as I am new with ajax. that's why I ask you to help me.