-1

This code keeps throwing an "unexpected token' error, but I can't figure out what is wrong with it. Any clues would be great.

function addComment() {
    $.ajax({
        url:'/add/comment/id',
        type:'POST',
        data.JSON.stringify({'Text':$('#comment_text').val()}),
        contentType:'application/json; charset=utf8',
        processData:false,
        success:function(data){
            $('#comments').prepend(data.comment.Text);
        }
    });
}
2
  • data : JSON.stringify({'Text':$('#comment_text').val()}), Commented Aug 6, 2012 at 1:50
  • oh man, that's embarrassing. Thanks. Commented Aug 6, 2012 at 1:51

3 Answers 3

5

The problem is on this line:

data.JSON.stringify({'Text':$('#comment_text').val()}), 

The unexpected token is the period (.) after data.

Instead of a period (.), you need a colon (:) after data, like so:

data: JSON.stringify({'Text':$('#comment_text').val()}), 

Note that you don't need JSON.stringify here. As @pst pointed out, jQuery does that for you anyways.

data: {
  'Text': $('#comment_text').val()
},
Sign up to request clarification or add additional context in comments.

Comments

3
data: JSON.stringify({'Text':$('#comment_text').val()}),

Comments

2
data.JSON.stringify({'Text':$('#comment_text').val()})

should be:

data: JSON.stringify({'Text':$('#comment_text').val()})

6 Comments

@MFB data can be an object or string. api.jquery.com/jQuery.ajax Best to let jQuery do the JSONing, since not all browsers have native JSON.stringify support
@CameronMartin the object will be transformed into key=value pairs not JSON
@Musa oh yes of course, my bad. A url-encoded query string makes much more sense in this situation than JSON.
@CameronMartin JSON makes it easy for me because I can throw it straight at my database, but I'm looking for an easy way to convert the string instead.
What database are you using? CouchDb?
|

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.