OhDaeSu
OhDaeSu

Reputation: 525

Rails: Syntax error: JSON.parse: unexpected character at line 2 column 1 of the JSON data

I am new to using ajax in ruby on rails. What I want: If a user clicks on a link with the class .link (to an external site, e.g. www.google.de), it should send data - namely the $(this).attr('id') - to my rails controller#action in posts/view. This is working fine (!), nevertheless I got a syntax error:

parsererror SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
Stack-Trace: jQuery.parseJSON@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9008:10
ajaxConvert@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9332:19
done@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9786:15
.send/callback@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:10303:8
fakeviews.self-2c717c6e0cc666118cfc1f98874e4c23dad3ccc9e219b4a857306ed44e947a7b.js:16:25

This is my assets/javascripts/views.js.erb

$(document).on("click", '.link', function() {
    var id = $(this).attr('id');
    $.ajax({
        url: "/posts/view", 
        cache: false,
        type: "GET",
        dataType: "json",
        data: { post_id: id }, // Here seems to be the problem?
        complete: function() {},
        success: function(data, textStatus, xhr) {
            alert("success");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
            alert("error");
        }
    });
});

When I delete the dataType: "json" the syntax error disappears. So what is going on exactly (since my code is working like I want, I am still wondering why there is the syntax error)?

This is my controllers/posts_controller.rb view action

def view
  @post = Post.find(params[:post_id])
  @post.views.create(user_id: current_user.id)

  respond_to do |format|
    format.html { redirect_to posts_path }
    format.js {render json: @post }
  end
end

Upvotes: 1

Views: 3449

Answers (2)

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON.

$.ajax({
             url: "/posts/view", 
            type: "POST",
        dataType: "json",
        headers: {
          'Content-Type': "application/json"
        }, 
        data: JSON.stringify({ post_id: id }), 

The syntax error while parsing is raised because Rails can't recognize passed data (since it's not a valid JSON string).

  • contentType specifies the format of data being sent to the server as part of request
  • dataType specifies the expected format of data to be received by the client(browser).

Also change the method from GET to POST. GET requests (at least usually) do not have a message body. If you're set it to GET it will be converted to parameters of URL string.

Upvotes: 2

elementzero23
elementzero23

Reputation: 1429

Your data should be a valid JSON string. You can verify if it's valid by pasting it here. To achieve a valid JSON string in your case, use JSON.stringify(JavaScriptObject):

$(document).on("click", '.link', function() {

var id = $(this).attr('id');
var dataObject = {};
dataObject.post_id = id;
$.ajax({
    url: "/posts/view", 
    cache: false,
    type: "GET",
    dataType: "json",
    data: JSON.stringify(dataObject)
    complete: function() {},
    success: function(data, textStatus, xhr) {
        alert("success");
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
        alert("error");
    }
});
});

Upvotes: 2

Related Questions