简体   繁体   中英

Rails ajax not returning json format

I am trying to use ajax to get information from my controller.

But it's not returning the json as I expect. Maybe I'ts a routing conflict, but not sure.

My controller:

class TicketsController < ApplicationController
  before_action :authenticate_user!
  respond_to :js, :json, :html
  //...
  def fill_category_select
    @category_by_system = Category.where(system_id: params[:sent_id])
    render json: @category_by_system
  end

my routes.rb:

  resources :tickets

  get 'tickets/fill_category_select/:sent_id', to: 'tickets#fill_category_select'

my script on a haml file:

:javascript
      $(document).ready( function(){
        $('#ticket_system').change(function(){
          $.ajax({
                  url: "fill_category_select", 
                 type: "GET",
             dataType: "json",
                 data: { sent_id:   $('#ticket_system').val() },
                 async: true,
              success: function(data, textStatus, xhr) {
                         for(var i in data){
                           var id = data[i].id;
                           var title = data[i].description;
                           $("#ticket_category").append(new Option(title, id));
                         }
                       },
              error: function(XMLHttpRequest, errorTextStatus, error){
                        alert("Failed: "+ errorTextStatus+" ;"+error);
                     }
            });
          });
        });

When I trigger the event and do the request it is:

REQUEST URL: http://localhost:3000/tickets/fill_category_select?sent_id=44

REQUEST METHOD: GET

STATUS CODE: 200 OK

TYPE: html

And the error returned and displayed the javascript alert is: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

It's like not hiting my fill_category_select, cause i've tried to put a raise 'error' and it just show the same error.

Does anyone can give me a direction?

---------- EDIT

I found the route line is not working.

when I add resources :tickets , except: [:show]

The request bring to me a "404 error", it's not simply an override problem, routing is not working at all.

And I still need to discovery what Im doing wrong. any suggestion?

in your routes.rb file, please replace existing one with this.

 get 'tickets/fill_category_select/:sent_id' => 'tickets#fill_category_select', defaults: { format: 'json' }

This will work i think

I solved it by adding:

  match 'tickets/fill_category_select/:sent_id' => 'tickets#fill_category_select', via: :get

for route my method fill_category_select

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