Question: AJAX request fails with internal server error in Sinatra app

Question

AJAX request fails with internal server error in Sinatra app

Answers 2
Added at 2016-12-15 17:12
Tags
Question

I'm creating a game in which a user's guess is sent to backend, where it is evaluated and then feedback in the form of an array is returned. I'm using AJAX to retrieve an array of data from a Sinatra back end. Here is the relevant call from my javascript file:

$("#form1").submit(function(e) {
    e.preventDefault();  // i've tried with and without this line
    $.ajax({
        type: "POST",
        url: "/guess",
        dataType: "json",
        data: { 
            guessData: choices, 
            secret: sessionStorage.getItem('secretcode')
        },  
        success: function(result) { 
            var response = JSON.parse(result);
            var html = "<span>" + response + "</span>";
            $('#response').append(html);
        },
        error: function (jqXHR, textStatus, errorThrown) {
           console.log(jqXHR.responseText)
        }
    })
});

Here is my Ruby code that returns the array:

post '/guess' do
    response = Guess.new(params)
    @response = response.feedback.to_json
end

Using Pry I've confirmed that the @response variable is '[0,2]'. I've entered this in JSONLint, which says that it is valid JSON. However, the response always goes the error route in the jQuery AJAX call and I get this error:

status 500 error

I've tried to implement the suggestions offered in other Stack Overflow questions with a similar issue but nothing seems to work.

Here is my log. It does not change during or after the AJAX request. All four entries occurred before the AJAX request.

server log

Answers to

AJAX request fails with internal server error in Sinatra app

nr: #1 dodano: 2016-12-15 17:12

Try it: Error is sending data:

$("#form1").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/guess",
      dataType: "json",
      data: {'guessData': choices, 'secret': sessionStorage.getItem('secretcode')},  
      success: function(result){
        var response = JSON.parse(result);
        var html = "<span>" + response + "</span>";
        $('#response').append(html);
      },
      error: function (jqXHR, textStatus, errorThrown) {
         console.log(jqXHR.responseText)
      }
    });
    }
nr: #2 dodano: 2016-12-21 17:12

The answer was that I needed to change the instance variable @response to a regular variable. The use of an instance variable to return the data must have caused an issue in the view because erb template uses instance variables for specific purposes.

  response = Guess.new(params)
  final_response = response.feedback.to_json
Source Show
◀ Wstecz