Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

How to pass json object to controller using ajax?

I have a json object.I want to create a new student by passing this value.How to pass the value of that object to controller using ajax in ruby on rails? This is the code i used for passing the object.

self.save = function() {
       var dataToSave = {
                    Name: self.firstName(),
                    _age: self.Age()
                 }
       alert(JSON.stringify(dataToSave))
         $.ajax({
        url: '/students/new',
        dataType: 'json',
        type: 'PUT',
        data: {total_changes: JSON.stringify(dataToSave)},
        success: function(data) {
            alert("Successful");
          },
          failure: function() {
            alert("Unsuccessful");
          }
        });
       // TODO send request
  };

}

i There is some error in terminal. It shows

Parameters: {"id"=>"new", "total_changes"=>"{\"Name\":\"hu\",\"_age\":\"7\"}"}

id is taken as new.Rake routes

[nithinv@ast297 jquery_country]$ rake routes
     students GET    /students(.:format)          students#index
              POST   /students(.:format)          students#create
  new_student GET    /students/new(.:format)      students#new
 edit_student GET    /students/:id/edit(.:format) students#edit
      student GET    /students/:id(.:format)      students#show
              PUT    /students/:id(.:format)      students#update
              DELETE /students/:id(.:format)      students#destroy

controller is

def new
    @student = Student.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @student }
    end
  end

How can i go to create function in the controller?

Upvotes: 1

Views: 2837

Answers (3)

Okky
Okky

Reputation: 10466

Try this url:

 alert(JSON.stringify(dataToSave))
     $.ajax({
    url: '/students',
    dataType: 'json',
    type: 'PUT',
    data: {total_changes: JSON.stringify(dataToSave)},
    success: function(data) {
        alert("Successful");
      },
      failure: function() {
        alert("Unsuccessful");
      }
    });

Change url to /students

Upvotes: 4

sjain
sjain

Reputation: 23356

I think that your routes.rb is having false routing and that is why you are getting id as new.

It should be:

routes.rb

resources "students" 

match "/students/new" => "students#new"

This will call new action in your students controller. So it depends that what code your new action has in the students controller.

The rest of your code seems to be right. But if you still get error than show the error message that you are getting and also the new action code further.

Upvotes: 0

Anton
Anton

Reputation: 3036

It does exactly what you ask it to do - converts JSON object into a valid string representation.

Now you need to parse this JSON string:

How do I parse JSON with Ruby on Rails?

Upvotes: 0

Related Questions