I want to be able to submit a form remotely (so the page does not refresh) and then have some javascript code get executed. Here's what I got so far
<script>
$(function() {
// Subscribe to receive messages!
var client = new Faye.Client('http://localhost:9292/faye');
// Our own private channel
var private_subscription = client.subscribe('<%=request.path + @id1.to_s + @id2.to_s%>',
function(data) {
$('<p></p>').html(data.username + ": " + data.msg).appendTo('#chat_room');
});
// Handle form submission to publish messages.
$('#new_message').submit(function(){ // THIS LINE GIVING TROUBLE
client.publish('<%=request.path + @id1.to_s + @id2.to_s%>', {
username: '<%= @user.fname+' '+@user.lname%>',
msg: $('#message_message').val()
});
// Clear the message box
$('#message_message').val('');
return false;
});
});
</script>
<div class="chat_container">
<div id="chat_room">
<p>Chat with <%= @other.fname+' '+@other.lname%> </p>
</div>
<%= simple_form_for Message.new, :id => "new_message",:controller => "messages", :action => "create", :remote => true do |f| %>
<%= f.text_field :message, :autocomplete => "off" %>
<%= f.hidden_field :sender_id, :value => @user.user_id %>
<%= f.hidden_field :receiver, :value => @other.user_id %>
<%= f.hidden_field :sent_at, :value => Time.now %>
<%= f.submit "Send", class: "btn btn-medium btn-primary" %>
<% end %>
</div>
If I change the name of my javascript function "#new_message" to anything else, the form submits properly into my database, but I lose the chatroom functionality. (The code that transmits the message to all clients in that chat room, via FAYE, and clears the text_box will not get called.)
If I keep the name of my javascript function "#new_message", the message will get transmitted to all clients in the chatroom, and the textbox will get cleared, but nothing will get stored into my database.
What can I do so that I can accomplish both the data storage and the chatroom functionality?
EDIT:Attempted this to no avail
$('#new_message').bind('ajax:success', function() {
client.publish('<%=request.path + @id1.to_s + @id2.to_s%>', {
username: '<%= @user.fname+' '+@user.lname%>',
msg: $('#message_message').val()
});
// Clear the message box
$('#message_message').val('');
return false;
});
});