I've been struggling to successfully create a "Post" using ajax. However, every time I attempt to do so, I encounter a "400 (Bad Request)" error. I am unsure whether the issue lies within the Rails website or my ajax request. The Rails setup is just a basic scaffold:
# POST /events
# POST /events.json
def create
@event = Event.new(event_params)
respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render :show, status: :created, location: @event }
else
format.html { render :new }
format.json { render json: @event.errors, status: 409 }
end
end
end
def event_params
params.require(:event).permit(:name, :consult, :description, :category, :likes)
end
Here is the Ajax code that I am trying to get to work:
$("button").click(function () {
$.ajax({
url: 'http://localhost:3000/events',
type: 'POST',
cache: true,
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { event: { name: "testname", consult: 72, description: "this is a test", category: "dance", likes: 23 } },
success: function (resp) {
alert(resp);
}
});