How to make Ember controller handle server validation errors? - validation

I use RESTAdapter with Ember Data. How to make Ember controller handle server validation errors? I think this code should be in the line "console.log(todo.errors);" but I have no idea how to achieve rendaring needed template...
App.TodosRoute = App.AuthenticatedRoute.extend({
model: function () {
return App.Todo.find();
}
});
App.TodosController = Ember.ArrayController.extend({
createTodo: function(todo) {
var data = this.getProperties('title', 'priority', 'due_date');
var todo = App.Todo.createRecord(data);
var self = this;
todo.on('becameInvalid', function(todo) {
// show errors on the form. code goes here
console.log(todo.errors);
});
todo.on('didCreate', function() {
// render list. code goes here
self.set('title', '');
self.set('priority', '');
self.set('due_date', '');
});
todo.save();
}
});
<script type="text/x-handlebars" data-template-name='todo/_edit'>
{{input type='number' class="input" placeholder="Priority" value=priority}}
{{input class="input" placeholder="What needs to be done?" value=title}}
{{input type='date' class="input" placeholder="Due date" value=due_date}}
</script>
<script type="text/x-handlebars" data-template-name="todos">
<section id="todoapp">
<header id="header">
{{partial 'todo/edit'}}
<button {{action "createTodo"}}>Save</button>
</header>
<section id="main">
<ul id="todo-list" class="sortable">
{{#each controller itemController='todo'}}
{{#unless isNew}}
<li {{bindAttr class="isEditing:editing"}} data-id="{{unbound id}}">
{{#if isEditing}}
{{partial 'todo/edit'}}
<button {{action "saveTodo"}} class="save-button">Save</button>
{{else}}
<label>{{priority}}</label>
<label>{{title}}</label>
<label>{{date due_date}}</label>
<button {{action "editTodo"}} class="edit-button">Edit</button>
<button {{action "removeTodo"}} class="destroy">Delete</button>
{{/if}}
</li>
{{/unless}}
{{/each}}
</ul>
</section>
</section>
</script>

Finally I got code like this:
App.TodosNewController = Ember.ObjectController.extend({
create: function() {
var data = this.getProperties('title', 'priority', 'due_date');
var todo = App.Todo.createRecord(data);
var self = this;
todo.on('becameInvalid', function(todo) {
self.set('model', todo);
});
todo.on('didCreate', function() {
self.set('priority', '');
self.set('title', '');
self.set('due_date', '');
self.transitionToRoute('todos');
});
todo.save();
}
});
Hope, it will help somebody

Related

Google recaptcha v3 recaptcha_response is null

i am using google recaptcha v3 in my website ,
here is the code i have added in my html web page in the head:
<script src="https://www.google.com/recaptcha/api.js?render=my public key"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('my public key', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
ecaptchaResponse.value = token;
});
});
</script>
and i added this in my form :
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
but when i submit the form and try to see the content of $_POST['recaptcha_response'] with var_dump()
it is just an empty string : string(0) ""
where is the mistake ?
thanks for answers !
i tried lots of changes but everytime i get " token = null " then i try this.. 100% working....
in Your Html
<html>
<head>
</head>
<body>
<form id="contact">
<div class="col-12">
<div class="form-group">
<input type="hidden" name="captcha_token" id="recaptchaResponse" data-sitekey="YOUR-SITE-KEY">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-lg" id="submit-btn">
SUBMIT
</button>
</div>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallbackV3&render=YOUR-SITE-KEY"></script>
</body>
</html>
after then add in your js file
$(document).ready(function(){
setInterval(function(){
ReCaptchaCallbackV3();
}, 90000);
$(document).on("submit",'#contact',function (e) {
var token = $('[name="g-recaptcha-response"]').val();
console.log(token);
});
});
var ReCaptchaCallbackV3 = function() {
grecaptcha.ready(function () {
grecaptcha.execute('YOUR-SITE-KEY', { action: 'contact' }).then(function (token) {});
});
}
In your original script you have a typo:
var recaptchaResponse = document.getElementById('recaptchaResponse');
ecaptchaResponse.value = token;
Instead of recaptchaResponse, you wrote ecaptchaResponse

Using ng-repeat after $http call

I'm learning Angular (1.6.6), so I'm hoping/assuming I'm missing something basic.
I'm populating a drop-down menu on ng-init, which is working as expected. I'm returning JSON from the DB, and console.log() shows me that the JSON is pulling through as expected.
I'm stuck with ng-repeat, trying to display the data in another div.
My Controller
app.controller('RandomTownCtrl', [
'$scope',
'$http',
function($scope, $http){
window.MY_SCOPE = $scope;
$scope.getAllRegions = function() {
$http({
method: 'GET',
url: '/all-regions'
}).then(function successCallback(response) {
$scope.regions = response.data;
}, function errorCallback(response) {
console.log('error');
});
};
$scope.getRandomTown = function() {
var guidEntity = $scope.guidEntity;
if (typeof guidEntity === 'undefined') { return };
$http({
method: 'GET',
url: '/region-name?region-guid=' + guidEntity
}).then(function successCallback(response) {
$scope.randomTown = response.data;
console.log($scope.randomTown);
}, function errorCallback(response) {
});
};
}
]);
The Markup
<div class="column col-sm-5 content-column">
<form ng-controller= "RandomTownCtrl" ng-init="getAllRegions()" ng-submit="getRandomTown()">
<h3>Generate Random Town</h3>
<div class="form-group">
<select name="nameEntity"
ng-model="guidEntity"
ng-options="item.guidEntity as item.nameEntity for item in regions">
<option value="" ng-if="!guidEntity">Choose Region</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Generate!</button>
</form>
</div>
<div class="column col-sm-5 content-column" id="output-column">
<div class="header">
<h4>Region Name:</h4>
</div>
<div ng-controller='RandomTownCtrl'>
<p ng-repeat="item in randomTown">
{{ item.name_region }}
</p>
</div>
</div>
You are mixing $scope and self together, you need also ng-repeat needs an array not an object.
$scope.randomTown = response.data;
Beginner Angular mistake: I didn't understand that the ng-controller directive created an isolate scope, and the output I was expecting wasn't happening because the data simply wasn't there in that scope.

vue2 call a parent function using $emit from component

i'm trying to call a parent methods from child component, but it seems not working.. here the code:
index.html
<div class="percorso"v-on:removeall="pathlengthTozero()">
</div>
component
Vue.component('lista-percorso', {
template:`
<div class="col-lg-2 col-xs-2">
<div class="removeall pull-right" v-on:click="removeall()"></div>
</div>`,
methods:{
removeall : function(){
this.listaSelezionati = [];
this.$emit('removeall');
}
}
parent method
pathlengthTozero : function(){
il_tuo_percorso = [''];
}
seems that "pathlengthTozero" is not called on emit which is the correct way to use it?
You need to put this v-on:removeall="pathlengthTozero" to the component <lista-percorso> like below,
<lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
and this.$emit will able to fire the parent method.
Sample Demo:
Vue.component('lista-percorso', {
template:`
<div class="col-lg-2 col-xs-2">
<div class="removeall pull-right" v-on:click="removeall()">xxxxxxxxxx</div>
</div>`,
methods:{
removeall : function(){
this.listaSelezionati = [];
this.$emit('removeall');
}
}
})
var App = new Vue({
el: '#app',
methods:{
pathlengthTozero : function(){
alert('hello');
il_tuo_percorso = [''];
}
}
});
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div class="percorso" ></div>
<lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
</div>
you should put the event listener on the child conponent where it is used
<div class="percorso">
<lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
</div>

go to a laravel controller using vue js's data

This is my vue
new Vue({
el: '#notificationMenu',
data: {
showModal: false,
patients: [],
duepatients: []
},
created: function(){
this.getPatients();
this.addUsers();
},
methods: {
getPatients: function(){
$.getJSON("{{route('api_patients')}}", function(patients){
this.patients = patients;
}.bind(this));
setTimeout(this.getPatients, 1000);
},
addUsers: function(){
this.$http.get('/govaccine/addUsers', '').then((response) => {
}, (response) => {
this.formErrors = response.data;
});
setTimeout(this.addUsers, 10000);
},sendSMS: function(val){
$.getJSON('sendsms/' + val,function(duepatient){
this.duepatients = duepatient;
}.bind(this));
}
}
});
and this is my html
<ul class="notifications-list" v-for="patient in patients">
<li class="item no-data">You don't have notifications</li>
<!-- use the modal component, pass in the prop -->
<modal v-if="showModal" #close="showModal = false">
<!--
you can use custom content here to overwrite
default content
-->
<h3 slot="header">custom header</h3>
</modal>
<a v-on:click="sendSMS(patient.due_date)">
<li class="item js-item " data-id="5" >
<div class="details">
<strong>#{{ patient.total}} patients</strong> are due for immunization on #{{patient.due_date}}
<span class="date">{{-- #{{patient.created_at}} --}}</span>
</div>
<button type="button" class="button-default button-dismiss js-dismiss">×</button>
</li>
</a>
</ul>
If I loop through vue js data using v-for how do i pass the data each loop in {{route('patient.show', parameter)}} so i can put a parameter on it.
or is there anyway to go to the controller and go to the other page?
yes you should use router-link. complete example here.
if I got you question wrong just tell me.

Getting Error in a chatroom that uses socket.io

I am using code as follow
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server Running...');
app.get('/',function (req, res)
{
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected to %s sockets connection', connections.length);
// Disconnect
socket.on('disconnect', function (data){
if(!socket.username) return;
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s socket connected', connections.length);
});
//Send Message
socket.on('send message', function(data){
console.log(data);
io.sockets.emit('new message', {msg: data});
});
// New user
socket.on('new user', function(data, callback){
callback(true);
socket.username = data;
console.log(socket.username);
users.push(socket.username);
updateUsernames();
});
function updateUsernames(){
io.sockets.emit('get users', users);
}
});
index.html -> Client
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://immodernafrican.move.pk:3000/socket.io/socket.io.js"></script>
<style type="text/css">
body{
margin-top: 30px;
}
#messageArea{
display: none;
}
</style>
</head>
<body>
<div class="container">
<div id="userFormArea" class="row">
<div class="col-md-12">
<form id="userForm">
<div class="form-group">
<label>Enter Username</label>
<input class="form-control" id="username"/>
<br/>
<input type="submit" class="btn btn-primary " value="Login">
</div>
</form>
</div>
</div>
<div class="row" id="messageArea">
<div class="col-md-4">
<div class="well">
<h3>Online Users</h3>
<ul class="list-group" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form id="messageForm">
<div class="form-group">
<label>Enter Message</label>
<textarea class="form-control" id="message"></textarea>
<br/>
<input type="submit" class="btn btn-primary " value="Submit">
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
var socket = io.connect('http://immodernafrican.move.pk:3000');
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $messageArea = $('#messageArea');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $users = $('#users');
var $username = $('#username');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data){
$chat.append('<div class="well">'+data.msg+'</div>')
});
$userForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $username.val(), function(data){
if(data){
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data){
var html = '';
for(i=0; i<data.length; i++)
{
html += '<li class="list-group-item">'+data[i]+'</li>';
}
users.html(html);
});
});
</script>
</body>
</html>
This is running accurately on localhost but as soon as i upload it to online hosting it gives an error. These are the error i am getting i have seen in console
(index):7 GET http://immodernafrican.move.pk:3000/socket.io/socket.io.js net::ERR_CONNECTION_TIMED_OUT
(index):58 Uncaught ReferenceError: io is not defined
at HTMLDocument.<anonymous> (http://immodernafrican.move.pk/:58:17)
at n (https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js:2:14784)
at Object.fireWith (https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js:2:15553)
at Function.ready (https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js:2:9773)
at HTMLDocument.B (https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js:2:14348)
i have tried to change
var socket = io.connect('http://immodernafrican.move.pk:3000');
to
var socket = io.connect();
but invain can anyone please help me regarding this issue so my chatroom can work
Thanks

Resources