Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending AJAX Post Jquery in rails application

With simple controller:

  def new
    @product = Product.new
    respond_to do |format|
      format.html #new.html.erb
      format.json { render json: @product}
    end
  end

  def create
    @product = Product.new(params[:product])
    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: "Save process completed!" }
        format.json { render json: @product, status: :created, location: @product }
      else
        format.html { 
          flash.now[:notice]="Save proccess coudn't be completed!" 
          render :new 
        }
        format.json { render json: @product.errors, status: :unprocessable_entity}
      end
    end
  end

and simple ajax request

$("h1").click ->
  $.post
    url: "/products/"
    data:
        product:
            name: "Filip"
            description: "whatever"

    dataType: "json"
    success: (data) ->
      alert data.id

im trying to send new product but server answers

[2013-07-09 18:44:44] ERROR bad URI `/products/[object%20Object]'.

and nothing changes in database. Why instead of getting /products uri its taking prducts/[oobject] thing? Whats wrong there?

like image 675
Filip Bartuzi Avatar asked Jul 09 '13 22:07

Filip Bartuzi


People also ask

How use jQuery AJAX in Rails?

In Rails, submitting an AJAX request can be done as easily as adding remote: true to a link, button, or form. From there you can have any response be some JavaScript code waiting on the server side, and it will execute in the client's browser. Here's the simplest code example of UJS via AJAX in a link.

Does AJAX use post?

post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.

How Ruby can be used with AJAX explain with example?

Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response.


1 Answers

Try this out:

CoffeeScript

$ ->
  $("h1").click ->
    $.ajax({
      type: "POST",
      url: "/products",
      data: { product: { name: "Filip", description: "whatever" } },
      success:(data) ->
        alert data.id
        return false
      error:(data) ->
        return false
    })

ES6-ified

$(() => $("h1").click(() => $.ajax({
  type: "POST",
  url: "/products",
  data: { product: { name: "Filip", description: "whatever" } },
  success(data) {
    alert(data.id);
    return false;
  },
  error(data) {
    return false;
  }
})));
like image 59
dasnixon Avatar answered Sep 27 '22 22:09

dasnixon