简体   繁体   中英

jQuery, Rails and Ajax POST to database

I wanted to do a POST request to the 'create' route, generated through scaffolding. The controller name is 'Translation' and the create route is '/translation'. In order to do that I created an ajax request with jQuery. My request looks like that -

$.ajax({
        type: "POST",
        url: "/translations",
        data: ?,
        success: function(msg){
        alert(msg);
        }
});

I want the data to include my paramaters, so that the translation generated will have these values. The translation's paramaters are 'source' and 'output'. Generated by scaffolding, the translation controller 'create' method looks like that -

  def create
    @translation = Translation.new(params[:translation])

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

I tried to insert different values to the data, yet it doesn't apply them. A new translation is created, but with no parameters. These are the data parameters I tried to insert so far in order to make the 'output' value 'hello' -

data: {'source':'hello'}
data: "source=hello"
data: {translations:{'source':'hello'}}

Try with

data = { translation : { source : 'hello' } }

But... are you using form helpers? it's easier to get this field correctly formatted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM