How to save values to database using AngularJS (Django Frame Work) - javascript

Hi my project works on Django framework with some use of AngularJS. What I need to achieve is when I click on submit on my page(html), it should save all the values I entered into the Database. I heard that I just need a simple submit button and main changes are in views.py. I am very new to Django as well as AngularJS. The following is my codes. Thanks in advance.
Html and AngularJS:
{% extends "base.html" %}
{% load static %}
{% block stylesheets %}
<link href="{% static 'css/xxg.css' %}" rel="stylesheet">
{% endblock %}
{% block mainbody %}
<br><br>
<div class="well">
<div class="well" ng-controller="LayerCtrl">
<table>
<tr>
<td>
<div class="input-group">
<span class="input-group-addon">jj</span>
<select class="form-control" name="jj">
{% for f in fab %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</div>
</td>
<td>
<div class="input-group">
{% for f in jj%}
{% if f == '1' %}
<span class="input-group-addon">yy</span>
<select class="form-control" ng-model="rr" ng-options="l.value as l.label for l in yyy"></select>
{% endif %}
{% if f == '8' %}
<span class="input-group-addon">tt</span>
<select class="form-control" ng-model="selected_technode" ng-options="l.value as l.label for l in rrr"></select>
{% endif %}
{% endfor %}
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">DD</span>
<!--<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">-->
{%verbatim%}
<select class="form-control" ng-model="selected_dd" ng-options="l as l for l in tt"></select>
{%endverbatim%}
</div>
</td>
</tr>
</table>
</div>
<div><h3>history:</h3></div>
<br/><br/>
<div ng-controller="AlertDemoCtrl">
<table class="table">
{% verbatim %}
<tr>
<td class="input-group" ng-repeat="(k,v) in alerts">
<span class="input-group-addon" ng-hide="v.hide">Check {{ k }}</span>
<span ng-hide="v.hide">
<input type="text" class="form-control" placeholder="Add gg here" ng-model="v.input">
<b>QQQ</b><input type="radio" name="{{ k }}" value="fc" ng-model="v.props">
<b>issue</b><input type="radio" name="{{ k }}" value="rr" ng-model="v.props">
<b>risk</b><input type="radio" name="{{ k }}" value="dr" ng-model="v.props">
<a type="reset" ng-click="reset()">
<span class="glyphicon glyphicon-repeat"></span>
</a>
<a href="" ng-click="remove(v)">
<span class="glyphicon glyphicon-trash"></span></a>
</span>
{% endverbatim %}
<tr>
<td>
<button type="button" class='btn btn-info' ng-click="addAlert()">
<span class="glyphicon glyphicon-plus"></span>
Add</button>
<button type="reset" ng-click="reset()" class="btn btn-danger">
<span class="glyphicon glyphicon-repeat"></span>
Reset All</button>
</td>
</tr>
</table>
</div>
<table class="table">
<!--IMPORT FILE-->
<tr>
<td>
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;' disabled>
</td>
</tr>
<!--ADD COMMENTS-->
<tr>
<td>
Add Comments*<div class="span5"><textarea name="bugnote_text" placeholder="Add comments here (max=600 characters)" rows="3" class="span10 ng-pristine
ng-valid ng-valid-maxlength" ng-maxlength="600"></textarea></div>
</td>
<td>
Add ftt*<input type="text" class="form-control" placeholder="Add ftthere">
</td>
</tr>
<form ng-submit="submit()" ng-controller="ExampleController">
<tr>
<td>
<button type="submit" id="submit" ngClick="Submit" class="btn btn-small btn-success"><span class="glyphicon glyphicon-pencil"></span> Submit</button>
<button class="btn btn-small btn-grey"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</td>
</tr>
</form>
</table>
</div>
{% endblock %}
{% block extrascript %}
{{ ngapp }}.controller("LayerCtrl", function ($scope, $http, $resource){
var layerresource_url = $resource("{% url 'api_list' 'v1' 'layer' %}");
console.log('initializing....')
$scope.$watch('yy', function () {
<!--alert($scope.yy);-->
$scope.update_layer();
});
$scope.update_layer = function(){;
console.log('Stage1: Initializing Primary Data... ');
layerresource_url.get({techtype__contains: $scope.selected, limit:1500},
function(data){
$scope.list = data['objects'][0]['layer'];
console.log($scope.layerlist);
},function(data, status){
console.log('Stage1: Internal error while loading initial data:'+status );
<!--alert('internal error');-->
}
);
};
});
{{ ngapp }}.controller("AlertDemoCtrl", function ($scope, $http, $resource){
$scope.alerts = [];
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!', props : 0, input : ""});
};
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
$scope.reset = function() {
angular.forEach($scope.alerts, function(v){
v.input = "";
v.props = 0;
});
};
$scope.remove = function(v){
v.hide = 1;
}
$scope.reset();
});
{% endblock %}

You can use AJAX if you don't want to use forms. In AngularJS, it would look like this. Note your controller should have the needed arguments:
$scope.addsomething = function() {
token = $window.localStorage.token;
//data to be submitted
$scope.data = {"name": $scope.name,"project": project_id,"some_url": someURL,"status": "1","type": 1};
$http.defaults.headers.common.Authorization = 'token '+$window.localStorage.token;
req = $http({
method: "POST",
url:"your_url/",
data:$scope.data,
headers: {
'Content-Type': 'application/json'
},
});
req.success(function(data,status) {
//do something on success
});
req.error(function(data, status, headers, config) {
//do something on error
});
}
On your backend you just have to point this URL to a view which will save it in the database. Hope this helps.

Related

How to update each div element with Ajax function using JQuery

I am new to JQuery and I have an Ajax function to update the select options. The Ajax is working fine on my first Div. But when I clone the div and run the Ajax call it again update the first Div element only not the element of cloned one. I new to closet... etc. Please help me so when I call the Ajax it will update the cloned div(current div) element.
this is my ajax function:
function acct_dbox() {
{#var that = $(this)#}
$.ajax(
{
type: "GET",
url: "/waccounts/getaccounts",
dataType: "json",
data: {
{#'acctlevel': $(this).val(),#}
'csrfmiddlewaretoken': '{{csrf_token}}'
},
success: function (data) {
$.each(data, function(index, item) {
if (item.length > 0){
console.log('test', item[0].AcctCode);
console.log('test', item[0].AcctName);
{#$("#id_accountcode option").remove();#}
$.each(item, function(index1, item1) {
console.log(item1.id);
console.log(item1.AcctCode);
console.log(item1.AcctName);
$("#id_accountcode").append($('<option/>',{
{#$("#id_accountcode").append($('<option/>', {#}
value: item1.AcctCode,
text: item1.AcctName
}));
})
$( document ).ready(function() {
acct_dbox();
var original_external_int_div = document.getElementById('account_list');
//Div to Clone
var clone = original_external_int_div.cloneNode(true); // "deep" clone
original_external_int_div.parentNode.append(clone);
acct_dbox(); # (it is updating the first div again - not cloned one)
});
My html is:
{% extends 'wstore_base_generic.html' %}
{% block content %}
<form action="" method="post" class="w-auto" id="new_trans_form"
xmlns:width="http://www.w3.org/1999/xhtml">
<div class="row mt-1 mb-4" >
<div class="col-md-12">
<div>
<div class="headerctr">
<h3>JV</h3>
<!-- <div> -->
<!-- <h3 > -->
<!-- </h3> -->
</div>
<div class="card-body" >
{% csrf_token %}
<div 38rem class="row style= width:18">
<div class="col">
<label>Transaction Date</label>
<input type="date" class="form-control" name="
{{form.fh_dt.name}}" value="{{current_date}}"
readonly>
{% if form.fh_dt.errors %}
{% for error in form.fh_dt.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col-sm" >
<label>Transaction Number</label>
<input type="number" class="form-control" name="
{{form.fh_no.name}}"
value="{{transaction_number}}" readonly>
{% if form.fh_no.errors %}
{% for error in form.fh_no.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<input type="hidden" class="form-control" name="
{{form.fh_type.name}}" required readonly
value="JV">
{% if form.fh_type.errors %}
{% for error in form.fh_type.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
<label>Transaction Ref.</label>
<input type="text" class="form-control" name="
{{form.fh_ref.name}}" required
value="Ref.">
{% if form.fh_ref.errors %}
{% for error in form.fh_ref.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
</div>
<div class="row mt-0">
<div class="col">
<label>Transaction Code</label>
<input type="text" class="form-control" name="
{{form.fh_code.name}}" required readonly
value="JV">
{% if form.fh_code.errors %}
{% for error in form.fh_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Detail</label>
<input type="text" class="form-control" name="
{{form.fh_detail.name}}" required
value="Detail">
{% if form.fh_detail.errors %}
{% for error in form.fh_detail.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction UserCode</label>
<input type="text" class="form-control" name="
{{form.fh_user_code.name}}" required
value="{% if form.fh_user_code.value %}
{{form.fh_user_code.value}}{% else %}{{request.user.username}}{% endif %}">
{% if form.fh_user_code.errors %}
{% for error in fh_user_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 mt-0">
<div class="card shadow">
<div class="card-header text-center">
<h3 class="headerctr">
Item Details
</h3>
</div>
<div class="card-body">
{% csrf_token %}
<table class="">
<thead class="thead-light">
<tr>
<th>Code</th>
<th class = "text-danger">Account</th>
<th class = "text-danger">Debits</th>
<th class="text-success">Credits</th>
<th class = "text-warning">Description</th>
<th class = "text-warning">Tax</th>
</tr>
</thead>
<tbody id="account_list" style="margin-bottom: 0">
<tr>
<td>
<select name="acct_code" class="form-control
fh_code" id="id_accountcode">
<option value="SELECT"
selected="selected">---SELECT---</option>
required></select>
</td>
<td>
<input type="text" name="acct_name"
class="form-control fh_name"
placeholder="Acct Code" readonly>
</td>
<td>
<input type="number" name="acct_debit"
class="form-control fh_debit"
placeholder=" " >
</td>
<td>
<input type="number" class="form-control
fh_credit" name="acct_credit"
placeholder=" ">
</td>
<td>
<input type="text" class="form-control
fh_detail" placeholder="Description"
name="acct_descript" >
</td>
<td>
<input type="number" class="form-control
fh_tax" name="acct_tax"
placeholder=" ">
</td>
<td>
<div class="btn-group">
<button type="button" id="btnadd"
class="btn add_new_row" title="Add">
<i class="fas fa-plus-square"></i>
</button>
<button type="button" class="btn
delete_row" title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td class = "text-success">Total Quantity:
<strong id="final_quantity">0</strong></td>
<td></td>
<td class = "text-success"> Total Price: <strong
id="final_price">0</strong></td>
</tr>
</tfoot>
</table>
</div>
<div class="col-md-12 mb-1">
<div class="btn-group">
<a href="{% url 'transactions' transtype='INV'
posted='ALL' %}" class="btn btn-info mr-2" >Cancel</a>
<input type="submit" class="btn btn-info submit_form"
name="save_next" value="Save&Print">
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
{#$("#id_accountcode").append($('<option/>', {#}
value: item1.AcctCode,
text: item1.AcctName
I made a change like:
$("table tbody select[name=acct_code]").append($('<option/>',
the all div selects get updated with option -Thanks to swathi.

Submit button are not submitting form as i have 2 buttons with ajax requests

I have a form with it is own submit button and there is a button inside that form that has the attributes type=button, onclick=somefunction().. the button with the onclick runs great but the other button is not submitting at all.
I've made sure that the button with the function on click have type=button and other button have type=submit
Here is my code:
{% extends 'base/base.html' %}
{% block content %}
<!-- Page Content -->
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<!-- page content -->
<br><br>
<h3>إنشاء فاتورة بيع جديدة </h3>
<br><br>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form method='post' autocomplete="off" action=".">
{% csrf_token %}
<div class="autocomplete" style="width:100%">
<b>هاتف العميل </b><br>
{{ create_sell_invoice.client }}
<br>
<p style="display: none;" id="shown_name">
client name
</p>
<div id="add_new_client" style="margin:25px;padding: 25px;display: none;">
<form method='POST'>
{% csrf_token %}
<small style="color:rebeccapurple;">يمكنك إضافة عميل جديد برقم هاتف جديد</small>
<br><br>
<b>إسم الطالب</b>
{{ add_client_from_invoice_form.student_name }}
<br><br>
<b>ولى الامر</b>
{{ add_client_from_invoice_form.parent_name }}
<br><br>
<b>العنوان</b>
{{ add_client_from_invoice_form.address }}
<br><br>
<b>الهاتف</b>
{{ add_client_from_invoice_form.phone1 }}
<br><br>
<b>المستوى</b>
{{ add_client_from_invoice_form.level }}
<br><Br>
<button type="button" class="btn btn-success form-control" onclick="sendingRequest()">
إضافة
</button>
</form>
</div>
</div>
<b id="id_delivery_title">التوصيل </b><br>
{{ create_sell_invoice.delivery }}
<br><br>
<b id="id_delivery_price_title">تكلفة التوصيل </b><br>
{{ create_sell_invoice.delivery_price }}
<br><br>
<b id="id_delivery_notes_title">ملاحظات على التوصيل </b><br>
{{ create_sell_invoice.delivery_notes }}
<br><br>
<button type="submit" id='ok_button' class="btn btn-primary form-control" disabled>موافق</button>
<br><Br><Br>
</form>
<script>
function sendingRequest() {
const studentName = document.getElementById('studentName');
const parentName = document.getElementById('parentName');
const clientAddress = document.getElementById('clientAddress');
const clientPhone = document.getElementById('clientPhone');
const clientLevel = document.getElementById('clientLevel');
$.ajax({
url: '/add/new/client/from/invoice/normal/invoice_sell_add/' + studentName.value + '/' + parentName.value + '/' + clientAddress.value + '/' + clientPhone.value + '/' + clientLevel.value + '/',
type: "POST",
data: {name: 'name', age: 'age'},
success: function (response) {
const add_new_client = document.getElementById('add_new_client');
add_new_client.setAttribute('style', 'margin:25px;padding: 25px;display: none;')
window.location.reload();
},
complete: function () {
},
error: function (xhr, textStatus, thrownError) {
}
});
}
</script>
<!-- /.col-lg-12 -->
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<datalist id="mylist">
{% for item in clients %}
<option>{{ item }}</option>
{% endfor %}
</datalist>
{% for item in clients %}
{{ item }}
{% endfor %}
<!-- ajax -->
<script>
$("#id_client").change(function () {
var number = $(this).val();
$.ajax({
url: '/ajax/getting_client_name/',
data: {
'number': number
},
dataType: 'json',
success: function (data) {
const shown_name = document.getElementById('shown_name'),
ok_button = document.getElementById('ok_button'),
add_new_client = document.getElementById('add_new_client');
if (data.client_name) {
shown_name.setAttribute('style', 'display:block;color: blue;');
shown_name.innerHTML = data.client_name;
ok_button.disabled = false;
add_new_client.setAttribute('style', 'margin:25px;padding: 25px;display: none;background-color: #d3e4ec;');
$('#id_delivery').fadeIn();
$('#id_delivery_title').fadeIn();
$('#id_delivery_price').fadeIn();
$('#id_delivery_price_title').fadeIn();
$('#id_delivery_notes').fadeIn();
$('#id_delivery_notes_title').fadeIn();
if (data.client_name === 'رقم الهاتف غير صحيح') {
shown_name.setAttribute('style', 'display:block;color: red;');
ok_button.disabled = true;
add_new_client.setAttribute('style', 'margin:25px;padding: 25px;display: block;background-color: #d3e4ec;');
$('#id_delivery').fadeOut();
$('#id_delivery_title').fadeOut();
$('#id_delivery_price').fadeOut();
$('#id_delivery_price_title').fadeOut();
$('#id_delivery_notes').fadeOut();
$('#id_delivery_notes_title').fadeOut();
}
}
}
});
});
</script><!-- end of ajax -->
{% endblock %}
The problem is in this line of code
<button type="submit" id='ok_button' class="btn btn-primary form-control" disabled>موافق</button>
where the button do nothing at all when clicked
Based on #hindmose comment the problem was having nested forms, I solved it by deleting the inner form tags and moved this part before the opening form tag .. now it is like :
<div id="add_new_client" style="margin:25px;padding: 25px;display: none;">
<small style="color:rebeccapurple;">يمكنك إضافة عميل جديد برقم هاتف جديد</small>
<br><br>
<b>إسم الطالب</b>
{{ add_client_from_invoice_form.student_name }}
<br><br>
<b>ولى الامر</b>
{{ add_client_from_invoice_form.parent_name }}
<br><br>
<b>العنوان</b>
{{ add_client_from_invoice_form.address }}
<br><br>
<b>الهاتف</b>
{{ add_client_from_invoice_form.phone1 }}
<br><br>
<b>المستوى</b>
{{ add_client_from_invoice_form.level }}
<br><Br>
<button type="button" class="btn btn-success form-control" onclick="sendingRequest()">
إضافة
</button>
</div>
<form method='post' autocomplete="off" action=".">
....

pass value to bootstrap modal form with django

When I use bootstrap modal for my form its only show first value.
here my template.html
{% for company in companys %}
<tr>
<td>{{ company.name }}</td>
<td>{{ company.desc }}</td>
<td align="center">
<button type="button" class="btn btn-warning margin-bottom" data-toggle="modal" data-target="#modal-default2">
delete
</button>
<div class="modal fade" id="modal-default2">
<div class="modal-dialog">
<form method="post" action="{% url 'system:company_delete' pk=company.pk %}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-body">
<input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}">
<input type="submit" class="btn btn-primary" value="Delete">
</div>
</div>
</form>
</div>
</div>
</td>
</tr>
{% endfor %}
its loop all the data, when click delete confirm form will popup. but its return same value.
but if without modal-bootstrap its work fine.
example: template.html
{% for company in companys %}
<tr>
<td>{{ company.name }}</td>
<td>{{ company.desc }}</td>
<td align="center">
<form method="post" action="{% url 'system:company_delete' pk=company.pk %}">
{% csrf_token %}
<input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}">
<input type="submit" class="btn btn-primary" value="Delete">
</form>
</td>
</tr>
{% endfor %}
it's work fine.
what I should do to make it work?...
update
views.py
# Company Crud
class CompanyListView(ListView):
context_object_name = 'companys'
model = models.Company
class CompanyCreateView(CreateView):
fields = ('name', 'desc')
model = models.Company
class CompanyUpdateView(UpdateView):
fields = ('name', 'desc')
model = models.Company
class CompanyDeleteView(DeleteView):
model = models.Company
success_url = reverse_lazy("system:company_list")
Your ajax modal will always return the same value inside modal because:
- Modal has this data-target="#modal-default2" as the target, however, your loop contains the modal body, with the id id="modal-default2", which will render modal as much as your loop goes.
So what you can do is to define a unique ID for each modal with the ID of each company modal-default{{company.id}}:
{% for company in companys %}
''' rest of codes '''
<button type="button" class="btn btn-warning margin-bottom" data-toggle="modal" data-target="#modal-default{{company.id}}">
delete
</button>
''' rest of codes '''
<div class="modal fade" id="modal-default{{company.id}}">
<div class="modal-dialog">
</div>
</div>
''' rest of codes '''
{% endfor %}
But this method is not effective if you have a lot of data, it will render lots of html codes.
Another option
With AJAX and one modal.
Your html would be:
{% for company in companys %}
<td>{{ company.name }}</td>
<td>{{ company.desc }}</td>
<button data-id="{{company.id}}" type="button" class="btn btn-warning margin-bottom delete-company" >
delete
</button> <!-- be aware of class 'delete-company' -->
{% endfor %}
{% csrf_token %}
<div class="modal fade" id="modal-default">
<div class="modal-dialog">
{% if company %} <!-- this company instance will come from AJAX -->
<form method="post" action="{% url 'system:company_delete' pk=company.pk %}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-body">
<input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}">
<input type="submit" class="btn btn-primary" value="Delete">
</div>
</div>
</form>
{% endif %}
</div>
</div>
AJAX
$(document).on('click','.delete-company',function(){
var id = $(this).data('id');
$.ajax({
url:'',
type:'POST',
data:{
'id':id,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
},
success:function(data){
$('#modal-default .modal-dialog').html($('#modal-default .modal-dialog',data));
$('#modal-default').modal('show');
},
error:function(){
console.log('error')
},
});
});
And your views would be:
change your url from CompanyListView.as_view() to companyListView
def companyListView(request):
context = {}
companys = models.Company.objects.all()
if request.method == 'POST' and request.is_ajax():
ID = request.POST.get('id')
company = companys.get(id=ID) # So we send the company instance
context['company'] = company
context['companys'] = companys
return render(request,'template.html',context)

How to add data from html to Database using AngularJS?

am using AngularJS/Django/Python for my project. One of my page taking inputs from the users through input fields and radio buttons and need to store those values to the database. How can I do that by using AngularJS? Thanks in advance.
html and JS:
{% extends "base.html" %}
{% load static %}
{% block stylesheets %}
<!--<html ng-app="ui.bootstrap.demo">-->
<link href="{% static 'bootstrap-v3.3.2/css/bootstrap.min.css' %}" rel="stylesheet" xmlns="http://www.w3.org/1999/html">
<link href="{% static 'bootstrap-v3.3.2/css/bootstrap-theme.min.css' %}" rel="stylesheet">
<link href="{% static 'css/screen.css' %}" rel="stylesheet">
<link href="{% static 'css/project.css' %}" rel="stylesheet">
<link href="{% static 'css/jquery-ui.css' %}" rel="stylesheet">
<link href="{% static 'css/ss.css' %}" rel="stylesheet">
<link href="{% static 'css/check_binning.css' %}" rel="stylesheet">
{% endblock %}
{% block mainbody %}
{% include 'orc_navigation_section.html' %}
<br><br>
<h1> <b>Check Binning Setup</b></h1><br>
<div class="well">
<div class="well" ng-controller="LayerCtrl">
<table>
<tr>
<td>
<div class="input-group">
<span class="input-group-addon">Fab</span>
<select class="form-control" name="fab">
{% for f in fab %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">Technode</span>
<select class="form-control" ng-model="selected_technode" ng-options="l.value as l.label for l in technodes"></select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">Layer</span>
<!--<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">-->
{%verbatim%}
<!--<select class="form-control" name="layer" >-->
<!--<option ng-repeat="l in layer_list" value="{{l}}">{{l}}</option>-->
<!--</select>-->
<select class="form-control" ng-model="selected_layer" ng-options="l as l for l in layerlist"></select>
{%endverbatim%}
</div>
</td>
</tr>
</table>
</div>
<div><h3>ORC binning setup history:</h3></div>
<br/><br/>
<!--Check fields and Radio Buttons-->
<div ng-controller="AlertDemoCtrl">
<table class="table">
{% verbatim %}
<tr>
<td class="input-group" ng-repeat="(k,v) in alerts">
<span class="input-group-addon" ng-hide="v.hide">Check {{ k }}</span>
<span ng-hide="v.hide">
<input type="text" class="form-control" placeholder="Add Check here" ng-model="v.input">
<b>Functional check</b> <input type="radio" name="{{ k }}" value="fc" ng-model="v.props">
<b>CFM issue</b> <input type="radio" name="{{ k }}" value="cfm" ng-model="v.props">
<b>Defect risk</b> <input type="radio" name="{{ k }}" value="dr" ng-model="v.props">
<a type="reset" ng-click="reset()">
<span class="glyphicon glyphicon-repeat"></span>
</a>
<a href="" ng-click="remove(v)">
<span class="glyphicon glyphicon-trash"></span></a>
</span>
{% endverbatim %}
<tr>
<td>
<button type="button" class='btn btn-info' ng-click="addAlert()">
<span class="glyphicon glyphicon-plus"></span>
Add Check</button>
<button type="reset" ng-click="reset()" class="btn btn-danger">
<span class="glyphicon glyphicon-repeat"></span>
Reset All</button>
</td>
</tr>
</table>
</div>
<table class="table">
<!--IMPORT FILE-->
<tr>
<td>
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;' disabled>
Choose File...
<input type="file" style='position:absolute;z-index:2;top:0;left:0;
filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'>
</a>
<span class='label label-info' id="upload-file-info"></span>
<button ng-click="uploadAttachFile()" class="btn btn-small btn-default" id="uploadfile" name="uploadfile" disabled>
<span class="glyphicon glyphicon-cloud-upload"></span> Import File</button>
</div>
</td>
</tr>
<!--ADD COMMENTS-->
<tr>
<td>
Add Comments*<div class="span5"><textarea name="bugnote_text" placeholder="Add comments here (max=600 characters)" rows="3" class="span10 ng-pristine
ng-valid ng-valid-maxlength" ng-maxlength="600"></textarea></div>
</td>
<td>
Add ECN*<input type="text" class="form-control" placeholder="Add ECN here">
</td>
</tr>
<form ng-submit="submit()" ng-controller="ExampleController">
<tr>
<td>
<button type="submit" id="submit" class="btn btn-small btn-success"><span class="glyphicon glyphicon-pencil"></span> Update check DB</button>
<button class="btn btn-small btn-grey"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</td>
</tr>
</form>
<!--<tr><td><div ng-controller="ModalDemoCtrl">-->
<!--<script type="text/ng-template" id="orc_enable.html">-->
<!--</script>-->
<!--<button type="button" class="btn btn-default" ng-click="open('lg')">Pop-up</button>-->
<!--</div></td></tr>-->
</table>
</div>
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
{% endblock %}
The .js file:
{% block extrascript %}
{{ ngapp }}.controller("LayerCtrl", function ($scope, $http, $resource){
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");
$scope.technodes = [
{'value': 22, 'label': 22},
{'value': 28, 'label': 28},
];
console.log('initializing....')
$scope.$watch('selected_technode', function () {
<!--alert($scope.selected_technode);-->
$scope.update_layer();
});
$scope.update_layer = function(){
console.log('Stage1: Initializing Primary Data... ');
layerresource_url.get({techtype__contains: $scope.selected_technode, limit:1500},
function(data){
$scope.layerlist = data['objects'][0]['layer'];
console.log($scope.layerlist);
},function(data, status){
console.log('Stage1: Internal error while loading initial data:'+status );
alert('internal error');
}
);
};
});
{{ ngapp }}.controller("AlertDemoCtrl", function ($scope, $http, $resource){
$scope.alerts = [];
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!', props : 0, input : ""});
};
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
$scope.reset = function() {
angular.forEach($scope.alerts, function(v){
v.input = "";
v.props = 0;
});
};
$scope.remove = function(v){
v.hide = 1;
}
$scope.reset();
});
{% endblock %}
and my view.py
class CheckBinningView(JSONResponseMixin, ListView):
template_name = "orc_enable.html"
model = OrcRecord
def get_context_data(self, *args, **kwargs):
context = super(CheckBinningView, self).get_context_data(*args, **kwargs)
fab = GroupProfile.objects.get(id=self.request.session['ACL_gid']).fab
gp = GroupProfile.objects.get(id=self.request.session['ACL_gid'])
layer = []
technode = []
for l in self.model.objects.raw('SELECT distinct layer, id FROM orc_orcrecord GROUP BY layer'):
layer.append(l.layer)
if fab == "ALL":
SQL = "SELECT distinct process_id, id FROM orc_orcrecord GROUP BY process_id"
else:
SQL = "SELECT distinct process_id, id FROM orc_orcrecord \
WHERE process_id LIKE '0" + fab +"%%' or process_id LIKE '" + fab + "%%' GROUP BY process_id"
print SQL
for t in self.model.objects.raw(SQL):
sql = "SELECT distinct process_id, id FROM orc_orcrecord GROUP BY process_id"
else:
sql = "SELECT distinct process_id, id FROM orc_orcrecord \
WHERE process_id LIKE '0" + fab +"%%' or process_id LIKE '" + fab + "%%' GROUP BY process_id"
print sql
for t in self.model.objects.raw(sql):
try:
technode.append(t.get_technode)
except Exception, e:
print e
continue
# for t in self.model.objects.filter(process_id__startswith=fab, is_main_record=True,
# mantis_id__isnull=False).values_list('id', flat=True).order_by('id').distinct()[:100]:
# technode.append(self.model.objects.get(id=t).get_technode)
# context['technode'] = gp.technology
context['fab'] = gp.fab
context['technode'] = list(set(technode))
# context['layer'] = list(set(layer))
context['technode'] = list(set(technode))
context['ngapp'] = "CMOD"
return context
You should look in this link about forms
will give you idea about ng-model. then you go the end points, see this resource api as you are using it.
You can use easily as:
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");
layerresource_url.field1 = "teste";
layerresource_url.field2 = true;
layerresource_url.field1.$save();
//will make a post to the URL passed in $resource
If you want to some customization:
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' % ,
{},{ save:{method:'POST'}}
}");
so you can just use like:
layerresource_url.save(model)
please read the link about resources.
you also have to setup the server side to accept the post.
There's a lot of steps here.
Your server (Django) needs to be available to receive the POST from the client.
Your client needs to capture user input. Angular is one way, but by no means the only way. If you're struggling with this, jQuery is far more accessible. If you're going to stick with Angular, look into ng-model like Alvaro mentions.
You need to make the POST. In Angular, you can do this with $resource and $http. Both are well documented. All you want is the vanilla POST, nothing fancy. Make sure the content of your form is in the body of your post.
You may run into Content-Type issues... you'll probably want your ContentType set to application/json; charset=utf-8 if you're working on js.

Jquery get href value into span balise

I need to get a href value into span balise like this
<p class="name">
<a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a>
</p>
ok i use jquery upload plugin so i want to insert some information in my database the informations are :the 2 hidden input, the textarea, the input ,text,the file name,and the url
<div id="Form" class="container1" style="display: none; width: 850px; height: 500px;">
<form id="fileupload" method="POST" enctype="multipart/form-data">
<span class='span' id=txt_lala></span>
<input type="hidden" name="anomalie" class="hide" id="anomalie" value="">
<input type="hidden" name="missionID" class="hide" id="missionID" value="<?php echo $_SESSION['mission_id']?>">
<fieldset class="fieldset1">
<table class="myTable" id="myTable">
<!--<input type="text" name="fait" id="fait" value="" class="text ui-widget-content ui-corner-all">!-->
<tr>
<td><label for="name">Recommandation:</label></td>
<td><textarea name="recommandation" id="recommandation" cols="50" ></textarea></td>
</tr><br>
<tr>
<td><label for="name">Constat:</label></td>
<td><textarea name="fait" id="fait" cols="50" ></textarea></td>
</tr>
</table><br>
<!-- Redirect browsers with JavaScript disabled to the origin page -->
<noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript>
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="fileupload-buttonbar">
<div class="fileupload-buttons">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="fileinput-button">
<span>Add files...</span>
<input type="file" name="files[]" multiple>
</span>
<button type="submit" class="start" >Start upload</button>
<button type="reset" class="cancel" >Cancel upload</button>
<button type="button" class="delete">Delete</button>
<input type="checkbox" class="toggle">
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="fileupload-progress fade" style="display:none">
<!-- The global progress bar -->
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
<!-- The extended global progress state -->
<div class="progress-extended"> </div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation"><tbody class="files"></tbody></table>
</fieldset>
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td>
<span class="preview"></span>
</td>
<td>
<p class="name">{%=file.name%}</p>
<strong class="error"></strong>
</td>
<td>
<p class="size">Processing...</p>
<div class="progress"></div>
</td>
<td>
{% if (!i && !o.options.autoUpload) { %}
<button class="start" disabled>Start</button>
{% } %}
{% if (!i) { %}
<button class="cancel">Cancel</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
<td>
<span class="preview">
{% if (file.thumbnailUrl) { %}
{% } %}
</span>
</td>
<td>
<p class="name">
<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
</p>
{% if (file.error) { %}
<div><span class="error">Error</span> {%=file.error%}</div>
{% } %}
</td>
<td>
<span class="size">{%=o.formatFileSize(file.size)%}</span>
</td>
<td>
<button class="delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>Delete</button>
<input type="checkbox" name="delete" value="1" class="toggle">
</td>
</tr>
{% } %}
</script>
</form>
and the jquery code is
jObjFormulaire.on( "submit", function(){
var fait = $( "#fait" ).val(),
anomalie = $( "#anomalie" ).val(),
missionID = $( "#missionID" ).val(),
recommandation =$( "#recommandation" ).val();
/*var element = $("#pnewanomalie");
alert(element);*/
var filedata = document.getElementsByName("name");
var i = 0, len = filedata.files.length;
// On file add assigning the name of that file to the variable to pass to the web service
var aa = $("#new_anomalie");
// alert(aa.length);
if(aa.length){
// alert('autreAnomalie');
if($("#new_anomalie").val()!=''){
var autreAnomalie = $("#new_anomalie").val();
var status = 'NEW';
// alert(autreAnomalie);
}else{
var autreAnomalie ='';
alert( "Veuillez donner le nom de la nouvelle anomalie." );
}
}
if ( fait == '' ){
alert( "Champs commentaire Obligatoire ! Soumission du formulaire annulée." );
$( jObjFormulaire.data( "checkbox" ) ).prop( "checked", false );
jObjFormDiv.dialog( "close" );
} else {
$.post("<?php echo $_SESSION['config']['businessappurl']?>index.php?display=true&module=Inspecteur&page=insertanomalie", {
fait1: fait,
anomalie1: anomalie,
missionID1: missionID,
autreAnomalie1:autreAnomalie,
status:status,
recommandation : recommandation
}, function(data) {
// $('#recommandation').val(data);
alert(data);
removeTableRow($("#myTable"));
$('#form')[0].reset(); // To reset form fields
location.reload();
// window.location.reload(true);
// $("#content").load('<?php echo $_SESSION['config']['businessappurl']?>index.php?display=true&module=Inspecteur&page=traitervolet&volet_id=<?php echo $_GET['volet_id']?>');
// $('#content').html(data);
});
//this.reset(); // To reset form fields
/*
* Comme le changement d'avis de l'utilisateur n'est pas géré,
* on peut l'empêcher de changer d'avis, mais ce n'est pas une bonne solution.
*/
$( "#pnewanomalie" ).remove();
$( jObjFormulaire.data( "checkbox" ) ).prop( "checked", true );
jObjFormDiv.dialog( "close" );
}
// Il faut bloquer la soumission traditionnelle
// du formulaire sinon la page est rechargée !
return false; // important !
});

Categories

Resources