faye messages are not displayed - ruby-on-rails

I made a simple faye tutorial application using this page:
http://code.tutsplus.com/tutorials/how-to-use-faye-as-a-real-time-push-server-in-rails--net-22600
And got a common problem with message displaying — server gets a parameter and renders it, but nothing happens on the page. I have alredy fixed faye.ru file, as was reccomended in comments. What should I do?
The most of the code is stored in a view:
<script>
$(function() {
// Subscribe to receive messages!
var client = new Faye.Client('http://localhost:9292/faye');
// Our public subscription
var public_subscription = client.subscribe('/messages/public', function(data) {
$('<p></p>').html(data.username + ": " + data.msg).appendTo('#chat_room');
});
// Our own private channel
var private_subscription = client.subscribe('/messages/private/<%= session[:username] %>', function(data) {
$('<p></p>').addClass('private').html(data.username + ": " + data.msg).appendTo('#chat_room');
});
// Handle form submission to publish messages.
$('#new_message_form').submit(function(){
// Is it a private message?
if (matches = $('#message').val().match(/#(.+) (.+)/)) {
client.publish('/messages/private/' + matches[1], {
username: '<%= session[:username] %>',
msg: matches[2]
});
}
else {
// It's a public message
client.publish('/messages/public', {
username: '<%= session[:username] %>',
msg: $('#message').val()
});
}
// Clear the message box
$('#message').val('');
return false;
});
});
<div class="chat_container">
<div id="chat_room">
<p class="alert"> Welcome to the chat room <%= session[:username] %>! </p>
</div>
<form id="new_message_form">
<input type="text" id="message" name="message">
<input type="submit" value="Send">
</form>
</div>

Okay, I replaced "rails s thin" by "rails server thin" and, by some sort of magic, it has started working since

Related

Submitting Form once but automatically being doubled / twice on POST method? ASP.NET MVC

I am currently working on a project in asp.net(v4.6) mvc(v5), it was working properly on first deployment on the remote server, after the first test trial its giving errors on forms when i submit on POST method.
It is automatically posting the form twice which is not required.
Places i checked for errors:
source code (also DEBUG)
searched and tried Logs
used tools to check why and from where this issue is occurring (no results)
I fix i found was the browser issue, when i changed from chrome to edge there was no errors... But there is still no notes on what the error is and how it is being generated.
Here is the View.cshtml
#using (Html.BeginForm("Create", "AdmissionCell", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#*Input Fields Here*#
<div class="form-group">
<div class="col-md-offset-4 col-md-6">
<input type="submit" value="Save Student Record" class="btn btn-primary btn-lg" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$("#CNIC").change(function () {
$.get("/AdmissionCell/CheckCNIC",
{ cnic: $("#CNIC").val() },
function (data) {
if (data === 1) {
//alert("Sorry, CNIC already exists, Please enter unique CNIC. or ");
//location.reload();
var cnicStu = $("#CNIC").val();
if (window.confirm('Sorry, CNIC already exists, Please enter unique CNIC or Press "Ok" to goto student details.')) {
window.location.href = "/AdmissionCell/Details?cnic=" + cnicStu;
};
}
});
});
});
</script>
<script>
$(function () {
$('.cnic').on('keyup', function () {
var input = $('.cnic').val();
if (input.length == 5 || input.length == 13) {
$('.cnic').val(input + '-');
}
});
$('.gcnic').on('keyup', function () {
var input = $('.gcnic').val();
if (input.length == 5 || input.length == 13) {
$('.gcnic').val(input + '-');
}
});
});
</script>
}
I suspect your jqueryval bundle is included twice.
Once in the view (as shown) and also in your _layout file, so the events are bound twice

E_WC_14: Accept.js encryption failed?

I have a payment form as follows
<body>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<div class="content">
<h1>Secure Checkout</h1>
<g:form name="paymentForm"
method="POST"
action="processAcceptPayment" >
<input type="text" name="cardNumber" id="cardNumber" placeholder="cardNumber"/> <br><br>
<input type="text" name="expMonth" id="expMonth" placeholder="expMonth"/> <br><br>
<input type="text" name="expYear" id="expYear" placeholder="expYear"/> <br><br>
<input type="text" name="cardCode" id="cardCode" placeholder="cardCode"/> <br><br>
<input type="hidden" name="dataValue" id="dataValue" />
<input type="hidden" name="dataDescriptor" id="dataDescriptor" />
<button type="button" onclick="sendPaymentDataToAnet()">Pay</button>
</g:form>
</div>
<g:javascript>
function sendPaymentDataToAnet() {
var authData = {};
authData.clientKey = "valid key";
authData.apiLoginID = "valid id";
var cardData = {};
cardData.cardNumber = document.getElementById("cardNumber").value;
cardData.month = document.getElementById("expMonth").value;
cardData.year = document.getElementById("expYear").value;
cardData.cardCode = document.getElementById("cardCode").value;
var secureData = {};
secureData.authData = authData;
secureData.cardData = cardData;
// If using banking information instead of card information,
// send the bankData object instead of the cardData object.
//
// secureData.bankData = bankData;
Accept.dispatchData(secureData, responseHandler);
}
function responseHandler(response) {
if (response.messages.resultCode === "Error") {
var i = 0;
while (i < response.messages.message.length) {
console.log(
response.messages.message[i].code + ": " +
response.messages.message[i].text
);
i = i + 1;
}
} else {
paymentFormUpdate(response.opaqueData);
}
}
function paymentFormUpdate(opaqueData) {
document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
document.getElementById("dataValue").value = opaqueData.dataValue;
document.getElementById("cardNumber").value = "";
document.getElementById("expMonth").value = "";
document.getElementById("expYear").value = "";
document.getElementById("cardCode").value = "";
document.getElementById("accountNumber").value = "";
document.getElementById("routingNumber").value = "";
document.getElementById("nameOnAccount").value = "";
document.getElementById("accountType").value = "";
document.getElementById("paymentForm").submit();
}
</g:javascript>
</body>
This generates the form as follows
I enter test credit card numbers and click Pay.
I get the following error in my javascript console.
I was just following the accept.js tutorial from the official page.
https://developer.authorize.net/api/reference/features/acceptjs.html
I appreciate any help as to the reason for this "Encryption Failed" error? Thanks!
UPDATE:
Ok so i did some more debugging. I put a test code "console.log("test");" inside responseHandler() function and noticed that it was called twice. I am now wondering why is responseHandler() being called twice.
When Accept.js triggers the callback function twice due to some other Javascript error occurring on the page, you can pretty quickly track down the source of that error on the by wrapping the contents of your callback function in a try/catch block:
Accept.dispatchData(secureData, responseHandler);
...
function responseHandler(response) {
try {
if (response.messages.resultCode === "Error") {
var i = 0;
while (i < response.messages.message.length) {
console.log(
response.messages.message[i].code + ": " +
response.messages.message[i].text
);
i = i + 1;
}
}
} catch (error) {
console.log(error);
}
}
Ok so i did some more debugging. I put a test code "console.log("test");" inside responseHandler() function and noticed that it was called twice. I am now wondering why is responseHandler() being called twice.
I repeated this test and can confirm that this is a common cause of this error. It is also true that Accept.js will mistakingly call your responseHandler() twice if it calls a function that has a Javascript error in it, or some other Javascript error is in the page. In my case, I had a sendOrder() AJAX function that was assuming a variable. Once I fixed that other function, the responseHandler() function was called only once.
The same error appeared to me too. Instead seeing the console, I go to the Network tab of Chrome browser and then see the success message has already appeared as below:
opaqueData
:
{dataDescriptor: "COMMON.ACCEPT.INAPP.PAYMENT",…}
Please note, while testing, enter the test cards for sandbox from https://developer.authorize.net/hello_world/testing_guide/

Quick Search Form Not Submitting MVC

I currently have a partial view that renders at the top of every page on the site. The point of this partial view is to provide a form that lets the user do a quick search. I have set the partial view form up as follows:
#using (Html.BeginForm())
{
<div class="col-md-7" style="text-align: right">
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.TextBox("caseReference")
<button type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
}
#Html.Partial("_MainNavigation")
</div>
</div>
</nav>
<script type="text/javascript">
$(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var request = { caseReference: $('#caseReference').val() };
submitForm(request, '#Url.Action("CaseSearch", "QuickSearch", new { area = "Search" })');
});
});
</script>
However under the page source the form action renders as a request to the home page with a post action. I have read numerous examples and this task seems very straight forward. Would it be a better idea to use the parameters on the #html.BeginForm() method?
So after spending a few hours researching, I have finally got the quick search functionality to work on the home page of my site. In the razorview I have the following code:
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.Kendo().MaskedTextBox().Name("name").Mask("000000/0000").Deferred()
<button id="search" type="submit">
<i class="fa fa-search"></i>
</button>
<script type="text/javascript">
$(function () {
$("#search").on("click", function (event) {
event.preventDefault();
var value = $('#name').val();
value = value.replace(/[/]/g, "_");
var refVal = value;
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
$.ajax({
type: 'GET',
url: url,
cache: false,
dataType: 'json',
contentType: "application/json;",
success: function (result) {
if (result.success) {
window.location.href = result.url;
}
else {
bootbox.alert(result.message);
}
}
});
});
});
However in regards to the following line:
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
If I hard code the url and append the search term it works on the Home page because we are at the root directory but from other pages it fails, To get around this I tried to use #Url.Action. However this is producing the following result in the html soure code:
var url = '' + '//' + refVal;
Is there a certain way to use the URL.Action method from withing JS?

How to clear a new record from ember.js frontend after it fails Rails validation (422 error)?

I'm working on a basic reddit clone app with Rails and ember.js (via the ember-rails gem). Basically I have a 'post' model/controller in Rails which works correctly, but when I add a new post from the ember post model's create action, even if it fails the Rails validation, if I then go to the 'posts' index page which lists all the posts, I can see it there (i.e. ember is keeping the data). When I refresh it goes away, but I'm wondering what is the best way to purge that data so that it gets deleted upon rejection from the backend? Another odd thing is that simply going to the posts/new page at all creates a new blank post which is then visible on the Then on the client-side, I have the following files in app/assets/javascripts/routes:
posts_route.js:
RedditJp.PostsRoute = Ember.Route.extend({
model: function() {
return this.get('store').find('post');
}
});
posts_new_route.js:
RedditJp.PostsNewRoute = Ember.Route.extend({
model: function(){
return this.get('store').createRecord('post'); },
actions: {
create: function() {
var newPost = this.get('currentModel');
var self = this;
newPost.save().then(
function() { self.transitionTo('posts'); },
function() { }
);
}
}
});
Here's the form I'm trying to use to submit the data in posts/new.hbs:
<h1> Add a post </h1>
{{#each error in errors.title}}
<p>{{error.message}}</p>
{{/each}}
<form {{action "create" on="submit"}}>
<div>
<label>
Title<br/>
{{input type="text" value=title}}
</label>
</div>
<div>
<label>
Address<br/>
{{input type="text" value=address}}
</label>
</div>
<div>
<label>
Vote count<br/>
{{input type="text" value=voteCount}}
</label>
</div>
<button>Save</button>
</form>
and then in assets/javascripts/templates/posts/ I have index.hbs:
<h1>Posts</h1>
<ul>
{{#each}}
<li>{{title}} at {{address}} vote count: {{voteCount}}</li>
{{else}}
<li>There are no posts.</li>
{{/each}}
</ul>
and here's my router.js:
RedditJp.Router.map(function() {
this.resource('posts', function() {
this.route('new')
});
this.resource('home', function() {
});
});
RedditJp.IndexRoute = Ember.Route.extend({
redirect: function(){
this.transitionTo('home')
}
});
I was thinking I could just add a check in the posts/index.hbs file and only show records that aren't dirty, but there must be a cleaner way of doing it, so I'm wondering what would be considered best practice in this case (I'm thinking there should be some code I could add to the promise in posts_new_route.js to deal with this, but I can't quite figure it out).
Thanks a lot! And let me know if you need any additional info.
You can check if model isNew in template to hide new Record ( also you can use isEmpty property )
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
In template will look like {{each model}}
{{#if model.get('isNew')}}
record.save().then(function(){
// Success callback
}, function() {
model..deleteRecord();
});

How to get text box value in ember.js

i have started to work on ember.js just day before.
i don't know how to get text box value while submitting. i have tried like this
this is html
<script type="text/x-handlebars" data-template-name="index">
<div >
<p>{{view Ember.TextField valueBinding="fname"}}</p>
</div>
<div>
<p>{{view Ember.TextField valueBinding="lname"}}</p>
</div>
<button {{action save}}>submit</button>
</script>
this is my ember.js file
App = Ember.Application.create();
App.IndexController = Ember.ObjectController.extend({
save:function()
{
var fname=this.get('fname');
var lname=this.get('lname');
alert(fname+','+lname);
}
});
whenever i am clicking on submit button, i am getting undefined in alert.so how to get value? i hope anyone will help me for to continue in ember.js
in js like this
App.WebFormController = Ember.Controller.extend({
fname: null,
lname: null,
save: function () {
var fname = this.get('fname');
var lname = this.get('lname');
alert(fname + ',' + lname);
}
});
without need a model
in template like this
<script type="text/x-handlebars" data-template-name="web_form">
<form {{action save on="submit"}}>
<div >
<p>{{input type="text" valueBinding="fname"}}</p>
</div>
<div>
<p>{{input type="text" valueBinding="lname"}}</p>
</div>
<button>submit</button>
</form>
</script>
Your problem is that your form doesn't have a model. You can provide it using model or setupController hook.
App.IndexRoute = Ember.Route.extend({
model: function() {
return {};
},
// or
setupController: function(controller) {
controller.set('model', {});
}
});
In addition some tips:
Use the action name on="submit" in the form, instead of action name in submit button. So you can execute the action when the user press enter key, in input.
And the input type="text" helper is a shortcut for view Ember.TextField
<script type="text/x-handlebars" data-template-name="index">
<form {{action save on="submit"}}>
<div >
<p>{{input type="text" valueBinding="fname"}}</p>
</div>
<div>
<p>{{input type="text" valueBinding="lname"}}</p>
</div>
<button>submit</button>
<form>
</script>
Here a live demo
That is really nice tutorial by mavilein.
We can do it at controller level also.
App.IndexController = Ember.ObjectController.extend({
content:function(){
return {fname:null,lname:null}
}.property(),
save:function()
{
var fname=this.get('fname');
var lname=this.get('lname');
alert(fname+','+lname);
}
});
Or we can do it
App.IndexController = Ember.ObjectController.extend({
fname:null,
lname:null,
save:function()
{
var fname=this.get('fname');
var lname=this.get('lname');
alert(fname+','+lname);
}
});
Below code is working for me:
cshtml: In script on tag specify data-template-name="text"
<script type="text/x-handlebars" data-template-name="text">
{{view Ember.TextField value=view.message}}
{{view Ember.TextField value=view.specy}}
{{textarea value=view.desc id="catdesc" valueBinding="categor" cols="20" rows="6"}}
<button type="submit" {{action "submit" target=view}}>Done</button>
</script>
app.js:
App.TextView = Ember.View.extend({
templateName: 'text',
message:'',
specy: '',
desc:'',
actions: {
submit: function (event) {
var value = this.get('specy');
var spc = this.get('message');
var de = this.get('desc');
}
}
});

Resources