user2158382
user2158382

Reputation: 4520

AJAX and Rails: Parsererror

I have an AJAX call to my rails API that only renders JSON and I keep getting a parsererror. I tried various things but nothing works.

Here is my ajax call

$.ajax('/api/users/show/:id', {
  type: 'GET',
  dataType: 'json',
  contentType: "application/json",
  data: {
    id: 1
  },
  success: function(response) {
    return alert("Hey");
  },
  complete: function(response, textStatus) {
    console.log(response);
    return alert("Hey: " + textStatus);
  }
});

Here is my API method

class UsersController < ApplicationController
    respond_to :json

    def show
        render :json => User.find(params[:id])
    end   

end

It seems like I am doing everything correct. I properly output JSON from the server, and I state in the AJAX call that I take JSON as expected input. Also, the AJAX call properly hits the server because I can see it in the server logs and it outputs a 200 status.

The problem is the AJAX call never runs success so I cant properly access the response variable I need.

Upvotes: 0

Views: 1456

Answers (1)

Khanh TO
Khanh TO

Reputation: 48982

When you specify dataType: 'json'. The returned data is already a javascript object. You should not parse it again using JSON.parse. Jquery will automatically parse the string from server before passing it to your success function. In your case, it could be that the JSON string from the server is not valid and jquery has error while parsing it and does not call your success function

Upvotes: 2

Related Questions