78506

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

Question:

{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?

Answer1:

<em><strong>Best practice</strong></em>

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 }

<em><strong>Solution</strong></em>

Then I think the error is in the following statement

params[:table1]

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

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

<strong>2.</strong> 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.

Answer2:

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: <a href="http://railscasts.com/episodes/54-debugging-ruby-revised?view=asciicast" rel="nofollow">http://railscasts.com/episodes/54-debugging-ruby-revised?view=asciicast</a>

This link may also help: <a href="https://stackoverflow.com/questions/18579143/advanced-ajax-with-ror-and-jquery-ui" rel="nofollow">Advanced Ajax with RoR and jQuery UI</a>

Answer3:

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. :)

Recommend

  • Rails: form submission isn't properly creating attributes?
  • Prevent users from voting multiple times in Rails
  • Calling a controller from another
  • Base Internationalization and “Could not find a storyboard named […]”
  • UITableView takes much longer to load when numberOfRows returns a large number
  • Rails 3, Custom Actions, and HTML request methods
  • Undefined navigator.push React-native 0.43.4
  • redirect_to root_url and return unless @user.activated
  • Can't remove headers after they are sent
  • Invalid object name 'dbo.Item'
  • Django invalid literal for int() with base 10
  • Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
  • TextToSpeech.setEngineByPackageName() triggers NullPointerException
  • Not able to aggregate on nested fields in elasticsearch
  • How to use JavaScript to determine whether a file exists in a directory?
  • How do I pass the string value parameter of the selected list item from an auto-populated dropdown l
  • Play WS (2.2.1): post/put large request
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • Incrementing object id automatically JS constructor (static method and variable)
  • Modifying destination and filename of gulp-svg-sprite
  • Deserializing XML into class C#
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • Javascript + PHP Encryption with pidCrypt
  • Apache 2.4 - remove | delete | uninstall
  • Is there a mandatory requirement to switch app.yaml?
  • Comma separated Values
  • How to get icons for entities from eclipse?
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • Error creating VM instance in Google Compute Engine
  • Free memory of cv::Mat loaded using FileStorage API
  • Hits per day in Google Big Query
  • how does django model after text[] in postgresql [duplicate]
  • Authorize attributes not working in MVC 4
  • unknown Exception android
  • JaxB to read class hierarchy
  • Busy indicator not showing up in wpf window [duplicate]
  • How to Embed XSL into XML
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF