4

Trying the basic stuff,

request with data and response with data and print it with jQuery and Rails

This is the front code.

$("#internal_btn").click(function() {
            //window.alert("clicked internal btn!");
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/room/test",
                //data: "{'data1':'" + value1+ "', 'data2':'" + value2+ "', 'data3':'" + value3+ "'}",
                data: {name:"ravi",age:"31"},
                dataType: "json",
                success: function (result) {
                //do somthing here
                    window.alert("success!!");
                },
                error: function (){
                    window.alert("something wrong!");
                }
            });
        });

in here, if the user clicks internal_btn this event happens and goes to the servide

room/test action.

ok this is fine. But I'm not sure how to send the data.

If i run this, i have an error like this.

MultiJson::LoadError

795: unexpected token at 'name=ravi&age=31'

Can i know what the problem is?

Also, is there are good example with this request and response with json format?

I googled a lot, but not satisfied with the result :(

2
  • can you show us your controller action that respond json data Commented Nov 20, 2013 at 4:56
  • Thanks for the response. I didn't make the controller action. First i'm trying to request to the controller and get the pararmeters from the front. Commented Nov 20, 2013 at 5:08

1 Answer 1

4

Try to use stringify your data or use GET method like,

data : JSON.stringify({name:"ravi",age:"31"}),

Full Code,

$.ajax({
     type: "POST",// GET in place of POST
     contentType: "application/json; charset=utf-8",
     url: "/room/test",
     data : JSON.stringify({name:"ravi",age:"31"}),
     dataType: "json",
     success: function (result) {
        //do somthing here
        window.alert("success!!");
     },
     error: function (){
        window.alert("something wrong!");
     }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thannks, i dont' know why, but i changed the type to "GET" and now it works. :)
To help others: I think the colleague has incorrect routes. Because of this, the code works when change from POST to GET.

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.