user5639219
user5639219

Reputation:

Rails update with ajax

Trying update post with ajax.

posts_controller.rb

def update
  if @post.update_attributes(post_params)
    flash[:notice] = 'Post updated!'
    redirect_to @post
  else
    flash[:alert] = 'Something wrong'
    render :edit
  end
end

application.js

$('.simple_form.edit_post').submit('submit', function (e) {
  e.preventDefault();
  form = $(this).serialize();
  $.ajax({
    type: 'POST',
    action: $(this).attr('action'),
    data: form,
    dataType: 'JSON'
  }).done(function (data) {
    alert(data.notice);
  }).fail(function (data) {
    alert(data.alert);
  });
});

When i try update i get error in Chrome console Page not found and alert output undefined

Upvotes: 1

Views: 3182

Answers (1)

Mauricio Coniglio
Mauricio Coniglio

Reputation: 96

First of all you should make a PUT/PATCH request instead of a POST request because you are making an update.

Also you should specify the url on the ajax request.

$('.simple_form.edit_post').submit('submit', function (e) {
    e.preventDefault();
    form = $(this).serialize();
    $.ajax({
        type: 'PATCH',
        url: '/posts',
        data: form,
        dataType: 'JSON'
    }).done(function (data) {
        alert(data.notice);
    }).fail(function (data) {
        alert(data.alert);
    });
});

Also, in your controller you should be able to respond to the ajax request in json format.

def update
  if updated = @post.update(post_params)
    flash[:notice] = 'Post updated!'
  else
    flash[:alert] = 'Something wrong'
  end

  respond_to do |format|
    format.html { updated ? redirect_to @post : render :edit }
    format.json { render json: flash.to_hash }
  end
end

Upvotes: 4

Related Questions