0

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()}), Aug 6, 2012 at 1:50
  • oh man, that's embarrassing. Thanks.
    – MFB
    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()
},
0
3
data: JSON.stringify({'Text':$('#comment_text').val()}),
2
data.JSON.stringify({'Text':$('#comment_text').val()})

should be:

data: JSON.stringify({'Text':$('#comment_text').val()})
6
  • 2
    @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 Aug 6, 2012 at 1:54
  • 1
    @CameronMartin the object will be transformed into key=value pairs not JSON
    – Musa
    Aug 6, 2012 at 2:13
  • @Musa oh yes of course, my bad. A url-encoded query string makes much more sense in this situation than JSON. Aug 6, 2012 at 2:15
  • @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.
    – MFB
    Aug 6, 2012 at 2:17
  • What database are you using? CouchDb? Aug 6, 2012 at 2:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.