1

I am working on AJAX requests between jQuery and Rails 3.1 (right now, working on localhost, testing in Chrome and Firefox, if this helps). When a user clicks on a link, I will pass the values of two text fields to the server. Specifically, I have a controller called AnswersController that will store these two values into the "answers" database table.

Below is my front-end code to make the request. The request is successfully received by Rails, as the response function in this request occurs and my paragraph called "last_chance" is filled by what the server responds with.

$('.other_question a').click(function(e) {          
        var this_profile_id = window.location.pathname.substring(1).split('/')[1];
        var this_question_id = window.location.pathname.substring(1).split('/')[3]; // there is a hidden space when splitting

        var ajax_data = {
            type : "PUT", /* should this be POST for older browsers? */
            url : '/profiles/' + this_profile_id + '/answers/' + this_question_id + '.json',
            contentType : 'json',
            dataType : 'json',
            success : function(msg) {
                alert("Data Saved: " + msg );
                $('#last_chance').text(msg['saved']);
            },
            data : {
                _method : 'PUT',
                page : {
                    authenticity_token : $('input[name=authenticity_token]').attr('value'),
                    answer : {
                        response : 'hi there',
                        comments : 'word'
                    },

                    action : 'update',
                    controller : 'answers',
                    profile_id : this_profile_id,
                    id : this_question_id
                }                   
            }               
        };
        $.ajax(ajax_data);
        return false;

    });

Here is my backend code to process this: the method is update in the AnswersController:

def update
    respond_to do |format|
       format.html { redirect_to 'http://google.com'}
       format.json { render :json => {:saved => 'ok: ' + params.to_s }.to_json }
     end

    return
end

Now, when I fill the "last_chance" paragraph element with the params that Rails received, it shows the following:

ok: {"action"=>"update", "controller"=>"answers", "profile_id"=>"11", "id"=>"42", "format"=>"json"}

It seems, unless something has happened that I'm not aware of, that Rails is not accepting or receiving these other parameters that I included in the AJAX call. Could someone explain to me why this is? And how I do I make sure that it receives all the included params?

Thank you very much in advance for any help!

Oh, also: I removed all the data parameters, and the same result was returned (meaning, I guess, that Rails handles the returned params). But how can I pass data then? Where did these custom params go?

EDIT: from a response's suggestion, I changed it to this:

    params[:saved] = 'OK'
    respond_to do |format|
        format.html { redirect_to 'http://google.com'}
        format.json { render :json => params.to_json }
    end

From this, the only output I got in the "last_chance" part was "OK". Where can I go from here?

2 Answers 2

1

Try to add additional parameters before render , like :

params[:saved] = 'ok: '
format.json { render :json => params.to_json }
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Vik, thanks for your response. I tried this and put the result in the EDIT part of my first post. It seems that the params hash is empty. Where can I go from here?
If params hash is empty than how are you getting response : ok: {"action"=>"update", "controller"=>"answers", "profile_id"=>"11", "id"=>"42", "format"=>"json"}. Just debug the params and print its value before and after adding new one params[:saved] = 'OK' . And check your log .
Hi Vik - I think I perhaps did some change incorrectly in your suggestion for this part. But I changed it so that all data was moved out of the "page" and into just the "data" itself, and everything seems to work now. Thank you for your contribution.
Also, I had to remove the contentType parameter - I saw this was done in an earlier thread, so I tried it at first - this did not work.
1

The type parameter for the ajax request should be 'POST', you set it specifically for rails backends with the _method data-parameter. If this doesn't fix the problem, can you post your relevant routes? Ah, and dont't set the contentType because the default is fine for your use case.

2 Comments

Hi mosch - it now works with PUT as the type. If I change it to POST (is that recommended?), should I just add another route for post that directs to my update action? Or can Rails do this automatically via my hidden _method param?
Well it looks to me as if rails isn't parsing your POST data at all, so it might have interpreted the request as a GET request? As it is not clear, what browsers do when you set type: "PUT", I would rather go with "POST" and _method: 'PUT' which is the Rails workaround.

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.