3

I have this controller method:

def create
    render plain: params[:article].inspect
    #@article = Article.new(article_params)

    #@article = Article.create(article_params)
    #if @article.save
    #   redirect_to @article    
    #else
    #   render 'new'
    #end
end

And this jquery ajax request:

function ajaxsend() {

  $.ajax({
    url: "/articles",
    type: "POST",
    data: { "article": { "title": "acme", "text": "text of the article" } },
    success: function(resp){ }
  });

}

But after I click the button that run e jquery ajax I get nothing. I expect the rendering but nothing happens, not even a error in the console. What am I doing wrong? I don't understand how can I send data thought jquery ajax to the controller. Any help? I'm new in ruby on rails development. Ruby version: 2.1.2; Rails version: 4.1.5;

Edit1:

It works well, when I do it in the traditional way in the form:

enter image description here

Result:

enter image description here

Edit2:

The WEBrick server prints this, when I press the button:

Started POST "/articles" for 127.0.0.1 at 2014-09-14 09:43:36 +0100
Processing by ArticlesController#create as */*
  Parameters: {"article"=>{"title"=>"acme", "text"=>"123 Carrot Street"}}
  Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.4ms | ActiveRecord: 0.0ms)

It seems ok. Why does nothing happens in the browser? Why the render in create method is not working? Any help?

The WEBrick response when I fill the form and press Create Article:

Started POST "/articles" for 127.0.0.1 at 2014-09-14 09:52:21 +0100
Processing by ArticlesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"o8bzaGFcWGaHFFEbgZsfx5bWiHDAIaX3j4xXh3XkTwc=", "article"=>{"title"=>"mmmmm", "text"=>"mmmmm"}, "commit"=>"Create Article"}
  Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.4ms | ActiveRecord: 0.0ms)

Edit3:

I also tried this way:

$.post("/articles", { "article": { "title": "Title1Ar", "text": "text of the article" } }, alert("callback"), "json").error(alert("error handler"));

This in the WEBrick:

Started POST "/articles" for 127.0.0.1 at 2014-09-15 09:19:49 +0100
Processing by ArticlesController#create as JSON
  Parameters: {"article"=>{"title"=>"firsttitle", "text"=>"text of the article"}}
  Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.5ms | ActiveRecord: 0.0ms)

but again nothing happens in the browser. Any help?

4
  • Have you tried adding remote: true as an option in the form helper? This would turn the POST into an AJAX request to your create or update action in the controller. You could then create an create.js.erb file in the articles view folder and it will run that JS. Commented Sep 14, 2014 at 0:18
  • I have done this simple form just to understand how am I able to invoke que create method with a jquery ajax request. Because I have a javascript tool developed to draw diagrams, but at the end I want to store all the diagram data. I have done it in PHP but now I have to do it in a ruby on rails app. To sum up, I have to store a json object into the server. Commented Sep 14, 2014 at 0:27
  • 1
    That looks like it should send the request, although you won't see any response in the browser. You mention not seeing an error in the console, are you referring to the Rails console (assuming you're running the WEBrick server), or the javascript console in the browser? Firebug in Firefox is indispensable for debugging these kinds of things. Commented Sep 14, 2014 at 3:52
  • Why do you say I won't see any responde in the browser? I don't have any error, either in the server or in the browser console (yes I'm running the WEBrick server). Any clue? Commented Sep 14, 2014 at 8:45

2 Answers 2

2

I make ajax call like this, you can try it:

$("#test-ajax-controller").on("click", function() {
  request = void 0;
  request = $.ajax({
    url: "/articles/create/?title=acme&text=123 Carrot Street"
  });
  request.done(function(data, textStatus, jqXHR) {
    console.log(data);
  });
  request.error(function(jqXHR, textStatus, errorThrown) {
    alert("AJAX Error:" + textStatus);
  });
});

And in your controller you should respond in JSON

respond_to do |format|
  format.json { render json: @your_return_object }
end 
Sign up to request clarification or add additional context in comments.

Comments

0

It seems ok. Why does nothing happens in the browser?

Because you've not created any functionality to handle the response.

Whenever you send Ajax requests, you'll always receive a response. This response is what you need to consider when writing your javascript. I'll detail an immediate fix for you, and then a more systemic fix which will set you on a better path:


Ajax

In line with your current setup, you'll want to receive the data back using the following:

#app/assets/javascripts/application.js
function ajaxsend() {

  $.ajax({
    url: "/articles",
    type: "POST",
    data: { "article": { "title": "acme", "text": "123 Carrot Street" } },
    success: function(resp){
       alert("Data");
    }
  });

}

The "alert" in this instance is what will create the effects you require. In order to make this work correctly, you'll have to use your own code (I don't know what you're trying to achieve).

It must also be noted that you'll have to bind this ajax code with an event in your JS:

#app/assets/javascripts/application.js
$(document).on("submit", "form", function() {
      $.ajax({
        url: $(this).attr("action"),
        type: "POST",
        data: $(this).serialize(),
        success: function(resp){
           alert("Data");
        }
      });
});

UJS

With Rails, we're very fortunate to have the Rails UJS driver, which provides a series of functionality for our Rails applications which we'll be able to invoke implicitly (IE without the need to keep defining functions).

You can see the Rails UJS Ajax functionality here

Specifically, you'll be able to do this:

#app/views/articles/new.html.erb
<%= form_for @article, remote: true do |f| %>

#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
   respond_to :js, :json, :html

   def create
      @article = Article.new article_params
      @article.save

      respond_with @article
   end

   private

   def article_params
      params.require(:article).permit(:title, :text)
   end
end

#app/assets/javascripts/application.js
$(document).on("ajax:success", "form", function(status, data, xhr){
   alert("DATA RECEIVED");
});

1 Comment

Thanks @RichPeck! With the example in the question I'm just trying to figure out how do save a json object. I have a javascript tool to draw diagrams that generates a json object in the end and I want to save it. I don't have a form I just have a json that needs to be saved in the database. In this simple example I'm trying to figure out how to do this, trying to save a simple json object (article) with jquery ajax. There is another way to do this? I think UJS way don't do what I want, because I don't have a form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.