user1141820
user1141820

Reputation: 99

How to send and store data to rails through jquery/ajax as a JSON object?

{QUESTION UPDATED}

I want to send some data to the server where rails is installed. My data is in JSON format such as:

var JSONObject=  {
             table1: {
                      title: "Title of text",
                      url: "Url of text"
                      }
                  }

and I use the following code in cilent:

$.ajax({
            type: "POST",
            url : "http://webadress.com/table1",
            cache: false,
            data: JSONObject,
             statusCode: {

                 200:function() { alert("200"); },
                 202:function() { alert("202"); }
            },
            success: function() {  alert("Data Send!");},
            error: function(xhr){  alert("The error code is: "+xhr.statusText);}        
        });

and in the cilent, the following code exists:

def create
    @table1= Table1.new(:title => params[:title], :url => params[:url])

respond_to do |format|
  if @table1.save
    format.html { redirect_to(@table1, :notice => 'User was successfully created.') }
    format.xml  { render :xml => @table1, :status => :created, :location => @table1}
    format.json { render :json => @table1}
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
    format.json  { render :json => @user.errors, :status => :unprocessable_entity }
  end
   end
end

But it is not working. How can I get data and store it in a database. I mean how can I put each element into different columns?

Upvotes: 0

Views: 6403

Answers (3)

Claudio Shigueo Watanabe
Claudio Shigueo Watanabe

Reputation: 1003

As it was a lot of time since the question was asked, I suppose my answer won't help the author but I hope I can help others with similar problem.

I basically replaced this code:

@table1= Table1.new(:title => params[:title], :url => params[:url])

With this one

@table1= Table1.new(params[:table1])

Using Firefox with Firebug (to debug the client side/javascript) with this RailCast (To debug RoR) helped me to debug and find an error in my code: http://railscasts.com/episodes/54-debugging-ruby-revised?view=asciicast

This link may also help: Advanced Ajax with RoR and jQuery UI

Upvotes: 1

rhetonik
rhetonik

Reputation: 1868

Since you're passing AJAX POST data as an object wrapped under the key table1, you should be able to read the object in your Rails controller's action as params[:table1]. You could modify this line:

@table1= Table1.new(:title => params[:title], :url => params[:url])

to

@table1= Table1.new(:title => params[:table1][:title]\
                  , :url => params[:table1][:url])

Also, you could add a fail-safe condition in the end to avoid NoMethodError should params[:table1] be unavailable.

@table1= Table1.new(:title => params[:title], :url => params[:url])\
         if params[:table1]

and further modify your if condition

if @table1.save

to

if @table and @table1.save

Hope this helps. :)

Upvotes: 0

basgys
basgys

Reputation: 4400

Best practice

First of all you should respond to json in the else statement, because if Table1 cannot be saved you are going to get a 406 (Not Acceptable) response code which is inappropriate. 422 (Unprocessable Entity) is appropriate.

format.json  { render :json => @user.errors, :status => :unprocessable_entity }

Solution

Then I think the error is in the following statement

params[:table1]

1. If your data are being sent like you said, you can do something like this

@table1= Table1.new(:title => params[:title], :url => params[:url])

2. And if you want to write clean code you should send data this way

table1: {
  title: "Title of text",
  url: "Url of text"
}

By wrapping your data in table1 you won't need to change anything.

Upvotes: 2

Related Questions