ember.js how to popup a modal from a controller - ember.js

I successfully use this code from a route to popup a boostrap model:
this.render("login-modal", {
into: 'application',
outlet: 'modal'
});
I have login template and the actions is handle through a controller. What I want to do is to pop the modal if the login is failed through the controller.
LoginController:
App.LoginController = Ember.Controller.extend({
needs: ['application'],
actions: {
submit: function() {
var username = this.get('username');
var password = this.get('password');
var self = this;
var postData = JSON.stringify({
"username": username,
"password": password
});
self.set('errorMessage', null);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'api/auth',
dataType: "json",
data: postData,
success: function(response){
self.set('errorMessage', response.message);
if (response.success) {
self.set('token', response.token);
self.set('loginstatus', 'success');
var appController = self.get('controllers.application');
appController.set('token', response.token);
self.transitionToRoute('/');
}
if (response.message) {
//console.log('login failed');
self.get('login').render("login-modal-failed", {
into: 'application',
outlet: 'modal'
});
}
},
error: function() {
alert("An error occurred while processing JSON file.");
}
});
}
}
this is the failed code:
if (response.message) {
//console.log('login failed');
self.get('login').render("login-modal-failed", {
into: 'application',
outlet: 'modal'
});
}
the error: Uncaught TypeError: Cannot read property 'render' of undefined
The Login template
<script type="text/x-handlebars" data-template-name="login">
<h1>LOGIN</h1>
<p>Please enter login info</p>
<form class="form-inline" role="form" {{action 'submit' on="submit"}}>
<div class="form-group">
{{input type="text" class="form-control" placeholder="Username" value=username}}
</div>
<div class="form-group">
{{input type="password" class="form-control" placeholder="Password" value=password}}
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
{{#if errorMessage}}
<br />
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<strong>Warning!</strong> Wrong username and/or password.
</div>
{{/if}}
</script>
The bootstrap modal component
<script type="text/x-handlebars" data-template-name="components/my-modal">
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{title}}</h4>
</div>
<div class="modal-body">
{{yield}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" {{action 'ok'}}>OK</button>
</div>
</div>
</div>
</div>
</script>
The bootstrap modal template based on the component above
<script type="text/x-handlebars" data-template-name="login-modal-failed">
{{#my-modal title='Login Failed' ok='failed'}}
Login failed - wrong username/password!
{{/my-modal}}
</script>

Related

Get value from ajax to view template without using form

I have a div class that get content from for loop queryset
<div class="form-group row">
<div class="col-md-4">Số hợp đồng</div>
<label class="col-md-8" id="so_hd_goc">{{hd.so_hd}}</label>
</div>
I want to use ajax to get the value from id="so_hd_goc" and send it to views:
my views:
def check_so_hd(request):
check_shd=request.GET.get("check_shd")
print("check_shd",check_shd)
return HttpResponse(check_shd)
my form:
<div class="card card-body">
<form method="POST" id = "save_bo_sung_sdt">
{% csrf_token %}
<div class="form-group row">
<div class="col-md-6">Người liên hệ</div>
<div class="col-md-6" id ="sdt_nguoi_lien_he" name="sdt_nguoi_lien_he">{{form1.nguoi_lien_he}}</div>
</div>
<div class="form-group row">
<div class="col-md-6">Số điện thoại</div>
<div class="col-md-6" id ="sdt_dien_thoai" name="sdt_dien_thoai">{{form1.dien_thoai}}</div>
</div>
<div class="form-group row">
<div class="card-footer" >
<button type="submit" class="btn btn-primary" id="save_phone" name="save_phone">Lưu số điện thoại</button>
</div>
</div>
</form>
</div>
my ajax:
<script>
const form1 = document.getElementById('save_bo_sung_sdt')
const sdtContainer = document.getElementById('sdt-body')
form1.addEventListener('submit', checkshd)
function checkshd(e){
e.preventDefault()
check_shd=document.getElementById(so_hd_goc)
$.ajax({
type: "GET",
url: "{% url 'check_so_hd' %}",
data:
{
check_shd:check_shd
},
success:function(data){
alert(data)
}
})
};
</script>
my url
path('check_so_hd', CallerViews.check_so_hd, name="check_so_hd"),
There is no error> just not print any result
Try this:
form1.addEventListener('click', (e) => {
e.preventDefault();
check_shd=document.getElementById('so_hd_goc').innerText;
console.log("check_shd=",check_shd);
$.ajax({
type: "GET",
url: "{% url 'check_so_hd' %}",
data:
{
'check_shd' : check_shd
},
success:function(data){
alert(data)
}
})
});

Django API shows 400 (Bad Request) error using angular4

I am using Django Rest API and calling it via Angular4
but I get the error when I try to upload an image I get bad request error
home.component.ts
hear I am using post method for uploading an image with data.
import { Component, OnInit } from '#angular/core';
import { Http, Response, Headers} from '#angular/http';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: Http) { }
homeObj:object = {};
addSaveData = function(home){
this.homeObj = {
"name" : home.name,
"email": home.email,
"subject": home.subject,
"message": home.message,
"image" : home.image,
}
let _url:string = 'http://127.0.0.1:8000/Home/Homemodel/';
this.http.post(_url, this.homeObj).subscribe(( res:Response) =>{
console.log(res);
})
}
ngOnInit() {
}
}
This is my home.component.html
it is angular4 code using as front-end for calling Django API.
<div id="headder" class="container"><h3>POST METHOD</h3></div>
<form class="container" id="formNewPost" name="formNewPost" #postData = "ngForm" (ngSubmit) = "addSaveData(postData.value)">
<div class="row">
<div class="col-sm-4">
<div style="width:100%"><label>Name:</label></div>
<input style="width:100%" type="text" name="name" id="name" placeholder="name" ngModel>
</div>
<div class="col-sm-4">
<div style="width:100%"><label>EMail:</label></div>
<input style="width:100%" type="text" name="email" id="email" placeholder="email" ngModel>
</div>
<div class="col-sm-4">
<div style="width:100%"></div><label>Subject:</label>
<input style="width:100%" type="text" name="subject" id="subject" placeholder="subject" ngModel>
</div>
<br>
<br>
<div class="col-sm-12">
<div style="width:100%"><label>Message:</label></div>
<textarea style="width:100%" type="text" name="message" id="message" placeholder="message" ngModel></textarea>
</div>
<input type="file" >
</div><br>
<input class="btn btn-primary" style="float: right;margin-bottom:15px;" type="submit" value="POST">
</form>

Doubts in general about ember components by a java developer

I created a panel component with a button which contains some actions in controller.
So the first doubt: What's the main difference between components and views?
I really dont know if i'm doing things in the correct way
First i created a "father" controller which will contain the method to send a panel action to the specified controller action
App.BasicArrayController = Ember.ArrayController.extend({
actions : {
panelActions : function(action) {
this.send(action)
},
},
});
App.BasicObjectController = Ember.ObjectController.extend({
actions : {
panelActions : function(action) {
this.send(action);
},
},
});
Next i created the controller which will extend the "father" and created a object which contains the name to display in panel and the name of action in controller
App.AlbumController = App.BasicObjectController.extend({
arrayActions : [Em.Object.create({name: 'Edit'},{action:'edit'}),Em.Object.create({name: 'Delete'},{action:'delete'})],
actions : {
edit:function(){
this.transitionToRoute('album.edit');
},
confirmDelete:function(){
this.get('model').deleteRecord();
this.get('model').save();
this.transitionToRoute('albums');
}
}
});
This is the correct way to extend a controller in ember?
Next i created the component template (.hbs) with bootstrap
<div {{bind-attr class=bootStrapClass}}>
<div class="panel-heading">
{{#if arrayActions}}
<div style="margin-top: -1.3%" class="btn-group pull-right">
<button type="button" class="btn btn-default dropdown-toggle"
data-toggle="dropdown">
Actions <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
{{#each arrayActions}}
<li><a href="#" {{action 'panelActions' this on='click'}}>{{name}}</a></li>
{{/each}}
</ul>
</div>
{{/if}}
<h3 data-toggle="collapse" data-parent="#accordion" {{bind-attr
href=hrefCollapseId}} {{action 'collapse' on='click'
}} class="panel-title">
<span {{bind-attr id=collapseId}}
class="glyphicon glyphicon-collapse-up">{{title}}
</h3>
</div>
<div {{bind-attr id=customId}} class="panel-collapse collapse in">
<div class="panel-body">{{yield}}</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" {{bind-attr id=myModalId}} tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button {{action 'cancelDelete'}} type="button" class="close"
data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Album</h4>
</div>
<div class="modal-body">Are you shure?</div>
<div class="modal-footer">
<button type="button"
{{action 'cancelDelete'}} class="btn btn-default"
data-dismiss="modal">Cancel</button>
<button type="button"
{{action 'confirmDelete' this}} class="btn btn-primary">Confirm</button>
</div>
</div>
</div>
</div>
Now the component .js
App.PanelPrimaryComponent = Ember.Component.extend({
setupIds: function(){
this.setProperties({
collapseId: "collapse" + this.get('customId'),
hrefCollapseId:"#" + this.get('customId'),
myModalId: "myModal" + this.get('customId')
});
}.on("init"),
actions : {
panelActions : function(obj) {
if(obj.action==="delete") this.send('delete');
else
this.sendAction('panelActions',obj.action);
},
delete:function(){
var jqueryModalId = "#"+ this.get('myModalId');
$(jqueryModalId).modal('toggle')
},
cancelDelete:function(){
this.set('deleteMode',false);
},
confirmDelete:function(){
$(".close").click();
this.sendAction('panelActions','confirmDelete');
},
collapse:function(){
var jQueryCollpaseId= "#"+this.get('collapseId');
if($(jQueryCollpaseId).hasClass("glyphicon-collapse-down")){
$(jQueryCollpaseId).removeClass("glyphicon-collapse-down").addClass("glyphicon-collapse-up")
}
else{
$(jQueryCollpaseId).removeClass("glyphicon-collapse-up").addClass("glyphicon-collapse-down")
}
}
}
});
Next a template which uses the component
<div class="col-xs-6">
{{#panel-primary title="Album" bootStrapClass="panel panel-success" customId="album" arrayActions=arrayActions panelActions='panelActions'}}
<span class="label label-default">Name: </span> {{name}} <span
class="label label-default">Description: </span> {{description}} {{/panel-primary}}
</div>
{{outlet}}
In general this is the best way to do that kind of component? What shold i do different in general?
Since i can have multiple panels i have to bind a dynamic id("collpase" and "modalId" , this is the correct way?
This is the best way to send that kind of action to controller in a component?
In general this is the best way to do that kind of component? What shold i do different in general?

ReferenceError: fav is not defined

I am a noob with emberjs and I am stuck at the issue for a while now. I created an itemController with the variable fav, but it keeps saying that it is not defined.
My index.html snippet looks like this:
<table class='table'>
{{#each model itemController='hotel'}}
<tr><td>
{{#if fav}}
<h4>{{title}}
<button {{action 'rmFav'}} type="button" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-heart"></span>
</button>
</h4>
{{else}}
<h4>{{title}}
<button type="button" class="btn btn-default btn-sm pull-right" {{action 'putFav'}}>
<span class="glyphicon glyphicon-heart-empty"></span>
</button>
</h4>
{{/if}}
<p> {{description}} </p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</td></tr>
{{/each}}
</table>
and my app.js has the following snippet related to the itemController:
App.HotelController = Ember.ObjectController.extend({
actions: {
putFav: function(){
this.set(fav,true)
},
rmFav: function() {
this.set(fav,false);
}
}
});
UPDATE: Just a clarification, I have an array of objects in json format in app.js file, and each object in it contains fav attribute.
Your problem is with HotelController you are referencing an undeclared variable fav in this.set(fav,...) you need to change to a string, like this.set("fav",...):
App.HotelController = Ember.ObjectController.extend({
actions: {
putFav: function(){
this.set("fav",true);
},
rmFav: function() {
this.set("fav",false);
}
}
});

Ember form values are undefined

I have a similar form, when I want to get submitted values in newItem controller, I get 'undefined' values. What's wrong?
<form role="form" {{ action 'add' target="newItem" on="submit"}}>
<h2>New category</h2>
<div class="form-group">
<label>Category title</label>
{{input value=title class="form-control" type="text" placeholder="Title"}}
</div>
<div class="form-group">
<label>Category description</label>
{{textarea value=description class="form-control" placeholder="Description"}}
</div>
<div class="form-group">
{{input type="submit" class="btn" }}
</div>
</form>
App.NewItemController = Ember.ObjectController.extend({
add: function(){
console.log(this.get('title')); // undefined
}
});
Update:
This form is on the ApplicationRoute:
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller, model) {
var newItem = this.controllerFor('NewItem');
controller.set('newItem', newItem);
}
});
You should try using Ember.TextField and Ember.TextArea:
<form role="form" {{ action 'add' target="newItem" on="submit"}}>
<h2>New category</h2>
<div class="form-group">
<label>Category title</label>
{{view Ember.TextField valueBinding="title"}}
</div>
<div class="form-group">
<label>Category description</label>
{{view Ember.TextArea valueBinding="description"}}
</div>
<div class="form-group">
{{input type="submit" class="btn" }}
</div>
</form>
The title and description values are now bound to the corresponding input fields.
Update:
I see your target is the newItem controller, so my guess is that this form is not bound to the NewItemController, thus the values are not bound to the NewItemController. A solution:
App.MyFormController = Ember.Controller.extend({
needs: ['newItem']
add: function(){
var newItemController = this.get('controllers.newItem');
newItemController.add(this.get('title'), this.get('description'));
}
});
App.NewItemController = Ember.ObjectController.extend({
add: function(title, description){
// add the new item here
}
});