0

enter image description hereI am new to ruby on rails. I am trying to add data to database using ajax post request. But I am not able to do so. So, can anybody help me to add data to PostgreSQL database.

<script>
    $(document).ready(function () {
        $('#submit-button').click(function() {
            $.ajax({
                url: "http://localhost:3000/batches",
                data: JSON.stringify({
                            name: $("#name").val(),
                            course_id: $("#course_id").val(),
                            start_date: $("#start_date").val(),
                            end_date: $("#end_date").val(),
                            status: $("#batch_status").val(),
                        }
                ),
                error: function(error) {
                 console.log(error);
                },
                success: function(data) {
                    console.log(data);
                },
                type: 'POST'
            });
        });
    })
</script>

And my code for controller is:

def new
    @batch = Batch.new
    respond_to do |format|
      format.html
      format.json
      end
  end

  def create
    @batch = Batch.new(batch_param)
    respond_to do |format|
       if @batch.save
        format.html { redirect_to @batch, notice: "Save process completed!" }
        format.json { render json: @batch, status: :created, location: @batch }
       else
          format.html {
            flash.now[:notice]="Save proccess coudn't be completed!"
            render :new
          }
          format.json { render json: @batch.errors, status: :unprocessable_entity}
      end
    end
  end
def batch_param
      params.require(:batch).permit(:name, :course_id, :start_date, :end_date, :status)
    end

And also let me know what am I doing wrong here. Or should I also have to add extra code for better operation. What changes should be done on routes and model for this operation?

These are the errors i have been getting...

enter image description here

Shital luitel
  • 135
  • 15
  • 2
    what's the error that you came across ? –  Jan 10 '17 at 12:06
  • can you post your batch_param method? – Ronan Lopes Jan 10 '17 at 12:32
  • it never moves to if part of create method. It always move to else part. But it is not only the problem, when I try to add data and check error in console log it shows different json file. "Object {readyState: 0, status: 0, statusText: "error"}". – Shital luitel Jan 10 '17 at 12:34

2 Answers2

0

You need to provide a batch param hash with the post

data: JSON.stringify({
    batch: {
        name: $("#name").val(),
        course_id: $("#course_id").val(),
        start_date: $("#start_date").val(),
        end_date: $("#end_date").val(),
        status: $("#batch_status").val(),
     }
}),

Because this is what batch_param requires

Also, you are posting as JSON, so you should post json data, not string data

So, replace the above with the following:

data: {
    batch: {
        name: $("#name").val(),
        course_id: $("#course_id").val(),
        start_date: $("#start_date").val(),
        end_date: $("#end_date").val(),
        status: $("#batch_status").val(),
    }
},
dataType: "JSON",

This will add the adequate headers to the post and RAILS will know this is JSON and the response will also be parsed as JSON.

Ruby Racer
  • 5,690
  • 1
  • 26
  • 43
  • Have you checked rails log? – Ruby Racer Jan 10 '17 at 14:03
  • Take a browse at [this link](http://guides.rubyonrails.org/debugging_rails_applications.html) – Ruby Racer Jan 10 '17 at 14:08
  • It is showing as "ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):" – Shital luitel Jan 10 '17 at 14:11
  • Started POST "/batches" for 127.0.0.1 at 2017-01-10 19:31:16 +0545 Processing by BatchesController#create as HTML Parameters: {"batch"=>{"name"=>"shitalluitel", "course_id"=>"9", "start_date"=>"2016-12-12", "end_date"=>"2016-12-14", "status"=>"1"}} Can't verify CSRF token authenticity. Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms) – Shital luitel Jan 10 '17 at 14:11
  • thank you it worked... but would you help me to over come this problem too – Shital luitel Jan 10 '17 at 15:00
  • DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. – Shital luitel Jan 10 '17 at 15:00
  • You should take this to a new question. Its version specific. Or search in this forum, the should be plenty of info. – Ruby Racer Jan 10 '17 at 15:02
0

Try this:

$.ajax({
  type: "POST",
  url: "http://localhost:3000/batches",
  data: {     
    batch: {
      name: $("#name").val(),
      course_id: $("#course_id").val(),
      start_date: $("#start_date").val(),
      end_date: $("#end_date").val(),
      status: $("#batch_status").val(),
      } 
    },
  error: function(error) {
            console.log(error);
            return false;
          },
  success: function(data) {
             console.log(data);
             return false;
          },
})
Rooby Doo
  • 166
  • 9