Skip to content

Commit

Permalink
POST DM form with ajax
Browse files Browse the repository at this point in the history
  • Loading branch information
tomykaira committed Jun 22, 2011
1 parent eb359de commit d60b7fa
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 15 deletions.
25 changes: 16 additions & 9 deletions app/controllers/tweets_controller.rb
Expand Up @@ -62,15 +62,12 @@ def create_message

# user check
if @tweet.user == current_user
redirect_to user_path, :notice => "自分は誘えません"
return
alert = "自分は誘えません"
end

# content check
if params[:message].blank? || params[:message].jsize >= 100
flash[:alert] = "入力内容を確認してください。(入力されていますか?長すぎませんか?)"
render :template => "tweets/new_message"
return
alert = "入力内容を確認してください。(入力されていますか?長すぎませんか?)"
end

# send DM / Mention
Expand All @@ -83,11 +80,21 @@ def create_message
Twitter.direct_message_create(@tweet.user.authentications.first.uid,
params[:message] + ENV['MESSAGE_SUFFIX'])
end
redirect_to user_path, :notice => "声をかけました"
rescue Twitter::Forbidden, Twitter::Unauthorized
flash[:alert] = "投稿に失敗しました"
render :template => "tweets/new_message"
return
alert = "投稿に失敗しました"
end

respond_to do |format|
if alert
format.html { render :template => "tweets/new_message" }
format.js { render :json => {:alert => alert},
:content_type => "text/json" }
else
notice = "声をかけました"
format.html { redirect_to user_path, :notice => notice }
format.js { render :json => {:notice => notice },
:content_type => "text/json" }
end
end
end
end
2 changes: 1 addition & 1 deletion app/views/tweets/_message_form.html.erb
Expand Up @@ -7,7 +7,7 @@
<%= @tweet.content %>
</div>
</div>
<%= form_tag message_tweet_path(@tweet) do -%>
<%= form_tag message_tweet_path(@tweet), :remote => true, :id => "message_form" do -%>
<div id="new_message_container" class="container clear">
<%= text_field_tag "message", params['message'] || "ご一緒させてください", :size=>50 %>(100字以内)<br />
<%= radio_button_tag :method, "DM", true %><%= label_tag "method_DM", "DM" %>
Expand Down
15 changes: 10 additions & 5 deletions public/javascripts/tweets.js
Expand Up @@ -15,12 +15,9 @@ function update(){

function displayError(data) {
$.each(["notice", "alert"], function(idx, attr) {
$("." + attr).detach();
if ( data[attr] ) {
if ( $("." + attr).length > 0 ) {
$("." + attr).text( data[attr] );
} else {
$("#header").after('<p class="'+attr+'">'+data[attr]+'</p>');
}
$("#header").after('<p class="'+attr+'">'+data[attr]+'</p>');
}
} );
}
Expand All @@ -43,10 +40,18 @@ $(document).ready( function() {
displayError(data);
update();
});

$( "a[data-remote]" )
.live( "ajax:success", function(ev, data, status, xhr){
if (typeof data === "string") {
$("#message").html(data);
$( "#message_form" )
.bind( "ajax:success", function(ev, data, status, xhr) {
if ( !data.alert ) { // success
$( "#message" ).html("");
}
displayError(data);
});
} else { // error
displayError(data);
}
Expand Down

0 comments on commit d60b7fa

Please sign in to comment.