简体   繁体   中英

Rails ajax error - SyntaxError: Unexpected token C in JSON at position 0

In my view file I have the following jQuery AJAX call

<% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>
.
.
.
function updateFunction() {
    var input = JSON.stringify({data: hot.getData()});

    $.ajax({
        type: 'POST',
        url: "/cars/create",
        data: input,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: create_data_succ,
        error: create_data_error
    });
}

function create_data_error(XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
}

In may cars_controller.rb I have

  def create
    Car.create(name: params[:data][:name])
    flash.now[:notice] = 'New Car!'
    render "new"
  end

Data is saving to db but I can't see the notice message on the screen, instead I am getting the alert message (error callback jQuery AJAX)

SyntaxError: Unexpected token C in JSON at position 0

what am I doing wrong? Any help much appreciated

The data is sent correctly to the controller, since the data saves to the DB; the error lies with the response. You're doing a render 'new' on a successful create, which sends HTML back as response to the AJAX call. Maybe something like:

car = Car.new(name: params[:data][:name])
unless car.save
   render json: { errors: error }
end
...

If you need both html and json response (for whatever reason) you can do this via respond_to

respond_to do |format|
   format.html  { render :new } 
   format.json  { render json: { ... } }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM