1

So I'm extremely confused on this. I have this coffeescript:

jQuery ->
     $('.message').click (e) ->
            e.preventDefault()
            href = $(location).attr('href')
            vote = { 'message': 'message': $('.messagebody').val(), 'photo_id' : href.substr(href.lastIndexOf('/') + 1)}
            $.ajax '../messages/',
                type: 'POST'
                dataType: 'json'
                data: JSON.stringify(vote)
                error: (jqXHR, textStatus, errorThrown) ->
                  # console.log(jqXHR)
                  # console.log(textStatus)
                   console.log(errorThrown)

                success: (data, textStatus, jqXHR) ->
                  $('.messagebody').val('')
                  console.log(vote)

When I fire this event my rails server receives this:

{"{\"message\":{\"message\":\"asdfasdfasdfasdfasdfasdfasdf\",\"photo_id\":\"1\"}
}"=>nil, "controller"=>"messages", "action"=>"create"}

And this is my controller that receives this parameter:

class MessagesController < ApplicationController
  before_filter :authenticate_user!
  def create
    @message = Message.new()

    logger.debug JSON.parse(params)
    @user = User.find_by_id(Photo.where(:id => params[:message][:photo_id]).pluck(:user_id))
    @message.photo_id = params[:message][:photo_id]
    @message.message = params[:message][:message]
    @message.user_id = @user.id
    @message.user_email = current_user.email
    @message.to_user = @user.email
    UserNotifier.send_message(@message).deliver
    respond_to do |format|
      format.json { render  json: '{"message": ok}' , status: :created}
    end
  end
end

When I try to parse the parameters I get this error

TypeError (no implicit conversion of ActionController::Parameters into String)

I've also tried not stringifying the data and just sending in the json, which my server is 100% fine with but the javascript returns this error:

SyntaxError: Unexpected token o

I'm not really sure what the issue is but I just need to resolve on of the errors and I've been trying to figure this out for hours and haven't found a solution yet.

1 Answer 1

3

How about if you try:

    jQuery ->
     $('.message').click (e) ->
            e.preventDefault()
            href = $(location).attr('href')
            vote = { 'message': $('.messagebody').val(), 'photo_id': href.substr(href.lastIndexOf('/') + 1)}
            $.ajax(
                { 
                    url: '/messages',
                    type: 'POST',
                    dataType: 'json',
                    data: vote,
                    error: (jqXHR, textStatus, errorThrown) ->
                        console.log(errorThrown)
                    success: (data, textStatus, jqXHR) ->
                        $('.messagebody').val('')
                        console.log(vote)
                }
            )

you should not have the need to serialize and deserialize the params. I noticed an error in your vote variable (the message key is repeated) and as for your url /messages should work just fine

I tried this pure js in my browser console, try this out in your console, just change the required variables

jQuery(function(){
    $('.message').click(function(e) {
            e.preventDefault();
            href = '/photos/123';
            vote = { 
                'message': 'text', 
                'photo_id': href.substr(href.lastIndexOf('/') + 1) 
            };
            $.ajax({
                url: '/foods',
                type: 'GET',
                dataType: 'json',
                data: vote,
                error: function(jqXHR, textStatus, errorThrown){
                    console.log(errorThrown);
                },
                success: function(data, textStatus, jqXHR){
                    $('.messagebody').val('');
                    console.log(vote);
                }
            });
    });
});
Sign up to request clarification or add additional context in comments.

8 Comments

I tried this but then I still get this error from the coffeescript SyntaxError: Unexpected token o, all the code in my controller runs fine but I'm trying to do something on success and the coffeescript throws an error that I can't figure out. The error has something to do with parsing the json I thought.
I've edited my answer to fix errors in the way $.ajax() function was being called
Same issue, SyntaxError: Unexpected token o at Object.parse (native). .. I've searched around and I get figure out what the problem is. To me it reads like it's trying to parse already parsed json? That's why I was stringifying it before, to try to get past this error.
I don't see why that would be the case. Let me add the pure js example I used to test this (I didn't actually test the coffee). Try using the same js directly in your browser's console and post the params hash as it its received in your controller
I went ahead and put it on the page itself and commented out all the coffee, I got the same error back.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.