0

I am trying to perform cross-platform request in rails.

My html code is :-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link type="text/css" rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
    <link type="text/css" rel="stylesheet" href="css/style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  
</head>
<body>
    <div class="container">
        <form class="new_batches" id="new_batch" accept-charset="UTF-8" >
            <div class="well">
                <div class="form-group row">
                    <label class="control-label col-md-2" for="name">Name </label>
                    <div class="col-md-4">
                        <input class="form-control" id="name" placeholder="Enter Batch Name" type="text" >
                    </div>
                </div>

                <div class="form-group row">
                    <label class="control-label col-md-2">Course ID</label>
                    <div class="col-md-4">
                        <input class="form-control" id="course_id" placeholder="Enter Your Course ID" type="text" >
                    </div>
                </div>

                <div class="form-group row">
                    <label class="control-label col-md-2">Start Date</label>
                    <div class="col-md-4">
                        <input class=" form-control" id="start_date" placeholder="Enter Start Date" type="text" >
                    </div>
                </div>

                <div class="form-group row">
                    <label class="control-label col-md-2"> End Date</label>
                    <div class="col-md-4">
                        <input class="datepicker form-control" id="end_date" placeholder=" Enter End date" type="text" >
                    </div>
                </div>
                <div class="form-group row">
                    <label class="control-label col-md-2">Status</label>
                    <div class="col-md-2">
                        <input name="batch[status]" type="hidden" value="0"><input type="checkbox" value="1" checked="checked"  id="batch_status"> Checked
                    </div>
                </div>

                <div style="margin-left: 110px;">
                    <button type="submit" id="submit-button" class="btn btn-primary ">Submit</button>
                </div>
            </div>
        </form>
    </div>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
<script>
 $(document).ready(function(){
  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    }
  });
 })
    $(document).ready(function () {
        $('#submit-button').click(function() {
            $.ajax({
       type: "POST",
       url: "http://localhost:3000/batches",
       beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
       xhrFields: {
        withCredentials: true
    },
       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",
     error: function(error) {
       console.log(error);
             },
     success: function(data) {
                console.log(data);
                return false;
             },
   })
        });
    })
</script>

And my backend code is as follow:-

class BatchesController < ApplicationController
          def new
            @batch = Batch.new
            respond_to do |format|
              format.json
              format.html
            end
          end

      def create
        @batch = Batch.new(batch_param)
        respond_to do |format|
           if @batch.save
             format.json { render json: @batch, status: :created, location: @batch }
             format.html { redirect_to @batch, notice: "Save process completed!" }
           else
              format.html {
                flash.now[:notice]="Save proccess coudn't be completed!"
                render json: @batch.errors, status: :unprocessable_entity
              }
              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

end

I also have added <%= csrf_meta_tag %> to myapplication.html.erb file.

but still i have been getting following error when i submit my form. so can anybody help me to solve this problem.

Started POST "/batches" for 127.0.0.1 at 2017-01-12 20:11:12 +0545
  ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by BatchesController#create as HTML
  Parameters: {"batch"=>{"name"=>"xyz", "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 13ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
Shital luitel
  • 135
  • 15

2 Answers2

1

If it makes sense, you can remove the csrf token verification. Just add this to your controller

skip_before_action :verify_authenticity_token
Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
0

in your ajax code you are using $('meta[name="csrf-token"]').attr('content')

that means you need something like this in you head tag

<meta content="code...=" name="csrf-token" />

which is missing.

You can also use

<input type="hidden" name="csrf-token" value="code..">

between your form tag

for csrf_code visit: Rails - How to add CSRF Protection to forms created in javascript?

Community
  • 1
  • 1
codenut
  • 683
  • 1
  • 7
  • 21