0

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.

2
  • what is the error? Also, the URL you're hitting doesn't look right. You really have show/:id in it? Commented Aug 3, 2013 at 8:12
  • statusText outputs parsererror Commented Aug 3, 2013 at 8:13

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I left that there on accident. Even after removing that I get the same parsererror
@user2158382: well then you need to check if the json string from the server is well-formed. As I said, jquery will parse it before passing to the success function. If there is any error when parsing, jquery may not call your success function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.