stackov8
stackov8

Reputation: 434

how make ajax-request through coffee script?

please help solve the problem.

albums controller:

  def create
    @album = current_user.albums.build(album_params)

    if @album.save
      flash[:success] = :album_saved
      redirect_to user_album_path(@current_user, @album)
    else
      flash.now[:error] = :album_not_saved
      render 'new'
    end
  end

html form:

<%= form_for [current_user, @album], remote: true do |f| %>
    <%= f.text_field :title %>
    <%= f.submit %>
<% end %>

layouts/_head.html.erb:

<title>Vd</title>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>

form it works. ajax-request create a new record in database.

I would like to add a message to the form. To do this I add the following code

assets/javascript/albums.coffee:

$(document).ready ->
  $("#new_album").on("ajax:success", (e, data, status, xhr) ->
    $("#new_album").append xhr.'<p>album add successfull</p>'
   ).on "ajax:error", (e, xhr, status, error) ->
    $("#new_album").append "<p>ERROR</p>"

As a result, the form is loaded on screen display follow eror message:

ExecJS::RuntimeError in Albums#new Showing /home/kalinin/rails/phs/app/views/layouts/_head.html.erb where line #3 raised: SyntaxError: [stdin]:8:32: unexpected string <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

Upvotes: 0

Views: 356

Answers (1)

Pavan
Pavan

Reputation: 33542

I don't know much about CoffeeScript but when looking into the Guides, it has the following code snippet

$(document).ready ->
  $("#new_article").on("ajax:success", (e, data, status, xhr) ->
    $("#new_article").append xhr.responseText
  ).on "ajax:error", (e, xhr, status, error) ->
    $("#new_article").append "<p>ERROR</p>"

So changing $("#new_album").append xhr.'<p>album add successfull</p>' to $("#new_album").append xhr.responseText should solve your problem.

Upvotes: 1

Related Questions