Getting updated values in ng-repeat Angular JS - javascript

I am using ng-repeat, which is getting values from my db and putting it. Now i insert these values into input text which i update. Now i have a save button, which saves the updated values. I am not getting the updated values when i press the save button. Please guide me through this.
<div ng-controller="education" ng-init="getEducationDetails();">
<div class="col-md-12">
<div class="row" ng-repeat="values in education"
style="margin-left: 20px; margin-right: 20px; margin-top: 10px;">
<div class="col-md-6">
<h4>
<small>Degree</small>
</h4>
<input type="text" id="educationDegree" name="educationDegree"
value="{{values.education_degree}}" style="width: 90%;" />
</div>
<div class="col-md-6">
<h4>
<small>Year</small>
</h4>
<input type="text" id="educationYear" name="educationYear"
value="{{values.education_year}}" style="width: 100%;" />
</div>
<div class="col-md-12" style="margin-top: 10px;">
<h4>
<small>University</small>
</h4>
<input type="text" id="educationUniversity"
name="educationUniversity"
value="{{values.education_university}}" style="width: 100%;" />
</div>
</div>
</div>
<div class="col-md-12" style="margin: 20px;">
<button ng-click="educationSave();" class="btn btn-default">Save</button>
</div>
</div>
on educationSave() i save the values. But when i get the education array in the educationSave() method, i get the old array. How can i get the updated array, after i adjust some of the input types
Here is how i get the values:
$scope.getEducationDetails = function()
{
$http({
method : 'GET',
url : '/getEducationDetails'
}).success(function(data, status, headers, config) {
$scope.education = data.resultSet;
alert($scope.education);
}).error(function(data, status, headers, config) {
});
};
Here is my controller method:
$scope.educationSave = function() {
var educationArray = JSON.stringify($scope.education);
//I then save this educationArray
};

The problem is that you are not using ng-model to bind your actual input value to controller. From documentation:
HTML input element control. When used together with ngModel, it provides data-binding, input state control, and validation.
Try something like this in your markup for each input:
<input type="text" id="educationDegree" name="educationDegree"
ng-model="values.education_degree" style="width: 90%;" />
See little Demo

Related

keep properties after jquery.load

I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question

jqWidgets: How can I post an HTML form inside a jqxWindow?

I created the following HTML form inside a jqxWindow widget for a Laravel project:
<div id="provinceWindow">
<div id="provinceWindowHeader"></div>
<div id="provinceWindowContent">
<form id="provinceForm" method="POST" action="{{route('province.store')}}">
{{ csrf_field() }}
<input type="hidden" name="provinceId" id="provinceId" value=""/>
<div class="form-group row">
<div class="col-6"><label>English province name</label></div>
<div class="col-6"><input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20"/></div>
</div>
<div class="form-group row">
<div class="col-6"><label>Spanish province name</label></div>
<div class="col-6"><input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20"/></div>
</div>
<br/>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3" />
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3" />
</div>
</form>
</div>
</div>
This is the javascript file:
$(document).ready(function () {
var datarow = null;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
//-----------------------------
// Window settings
//-----------------------------
$('#provinceWindow').jqxWindow({
autoOpen: false,
isModal: true,
width: 400,
height: 160,
resizable: false,
title: 'Province name',
cancelButton: $('#cancelBtn'),
initContent: function () {
$('#submitBtn').jqxButton();
$('#submitBtn').on('click', function () {
$('#provinceForm').submit();
});
}
}).css('top', '35%');
The file routes\web.php has only one resourse route defined for this page:
// Routes for province maintenance
Route::resource('province', 'provinceController');
Checking the available routes with php artisan route:list command, I get these:
Method URI Name Action
GET|HEAD / APP\Http\Controllers\homeController#index
GET|HEAD province province.index APP\Http\Controllers\provinceController#index
POST province province.store APP\Http\Controllers\provinceController#store
GET|HEAD province/create province.create APP\Http\Controllers\provinceController#create
GET|HEAD province/{province} province.show APP\Http\Controllers\provinceController#show
PUT|PATCH province/{province} province.update APP\Http\Controllers\provinceController#update
DELETE province/{province} province.destroy APP\Http\Controllers\provinceController#destroy
GET|HEAD province/{province}/edit province.edit APP\Http\Controllers\provinceController#edit
My controller action:
public function store(Request $request)
{
$fields = $request->all();
if ($request->provinceId == '') {
$province = new province($fields);
$validator = Validator::make($fields, $province->rules());
if ($validator->fails()) {
return redirect('')->withErrors($validator)->withInput();
}
else {
$province->save();
}
return view('province/index');
}
}
The form is shown on top of a jqxGrid widget, as a modal window, in order to capture the required information and perform the CRUD operations for the corresponding DB table.
The problem is, when I click the "Submit" button the window is closed and nothing else happens. The form is not posted to the indicated action and the data entered get lost.
It does not matter if I initialize the submitBtn inside the initContent or outside of it. The form is never posted.
I also tried the Close event of the jqxWindow to no avail.
If I take a look to the generated HTML it looks like this:
<form id="provinceForm" method="POST" action="http://mis:8080/province">
<input type="hidden" name="_token" value="Y9dF5PS7nUwFxHug8Ag6PHgcfR4xgxdC43KCGm07">
<input type="hidden" name="provinceId" id="provinceId" value="">
<div class="form-group row">
<div class="col-6">
<label>English province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20">
</div>
</div>
<div class="form-group row">
<div class="col-6">
<label>Spanish province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20">
</div>
</div>
<br>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3 jqx-rc-all jqx-button jqx-widget jqx-fill-state-normal" role="button" aria-disabled="false">
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3">
</div>
</form>
Pressing the submit button takes me to the home page and nothing gets added to the DB table.
I guess the issue has something to do with Laravel routes because I get no errors.
What is missing or what is wrong with this approach?
Any light is appreciated.
Alright, because I erroneously added in my Model a validation, that was not needed, for a column (there was already a constraint defined at the DB table level), it was not possible to fulfill the validator when saving a new record. I commented that line in my Model and, that was it!
protected $rules = array(
'provinceNameEn' => 'required|alpha|max:20',
'provinceNameSp' => 'required|alpha|max:20'
//'deleted' => 'required|in:M,F' // This is already validated in a DB constraint.
);
I noticed the control was returned to my home page but without any message or error, but if you pay attention to my controller it was precisely the behavior programmed. However, there is no implementation to display the error messages, so I added dd($validator); before that return statement. There I read the message and finally found the solution.

Replacing files in input using Vue.js

I have Vue.js template file with data that contains documents. My page has table. Table has rows with input buttons upload file, like this
<tr v-for="(doc, index) in documents">
<td :id="'doc-' + doc.id" v-show="doc.visible">
<div class="row">
<div class="col-md-9">
<a v-if="doc.document" :href="doc.document.file" v-text="doc.name"></a>
<div v-else v-text="doc.name"></div>
</div>
<div class="col-md-3">
<div class="row">
<div v-if="doc.document" class="col-md-8">
<label :for="'upload_doc_' + doc.id">
<span class="glyphicon glyphicon-upload text-primary" role="button"> Upload</span>
<input type="file"
:id="'upload_doc_' + doc.id"
class="hidden"
#change="replaceDoc($event, index)"
/>
</label>
</div>
</div>
</div>
</div>
</td>
So, some rows may contain some files and some not. But button should replace or add file to the row. So i wrote method:
methods: {
replaceDoc (event, index) {
this.documents[index] = event.target.files[0]
},
But it seems that it does not contain any data, when I'm trying to send it to server it sends empty dictionary.
Have you tried using Vue.set or this.$set
Instead of:
this.documents[index] = event.target.files[0]
Try this:
this.$set(this.documents, index, event.target.files[0]);
OR
Vue.set(this.documents, index, event.target.files[0]);
You can refer to this API.

How to get my form submitted via jQuery/ajax?

I'm trying to submit a form via jquery so that the whole page won't reloads. I'm following the instruction on jQuery.post() guide but so far it's not working. Here's what I'm looking for to complete this task.
Submit the form to a ColdFusion proxy page and from their it will send the data as json via CFHTTP.
During the process of submitting the form, show a progress gif or status.
Somehow, hide or remove the form off of the page.
Show a success or thank you message on the page where the form used to be.
So far the form I have did not even find the values from the input. The error says that "TypeError: $form.find(...).value is not a function". Below is my JavaScript code thus far:
$(function(){
$("##frmComment##").submit(function(event){
event.preventDefault();
$("##submitResponse").append('<img src="http://st2.india.com/wp-content/uploads/2014/07/ajax-loader.gif" class="progressGif">');
// Cache $form, we'll use that selector more than once
var $form=$(this);
var data = $form.serialize(); //get all the data of form
//post it
$.post(
"/customcf/knowledgeOwl/proxyPost-KB.cfm",
data,
//console.log(response),
function(response){
// Success callback. Remove your progress gif, eg:
//$('body').removeClass('in-progress');
console.log(response);
// Remove the spining gif from the div
$("##submitResponse img:last-child").remove();
//Remove the feedback form
$("##frmComment").remove();
$form.fadeOut('slow', function(){
//Add response text to the div
$("##submitResponse").append("<h6>Thank you for your feedback.</h6>");
$("##submitResponse").html(response).fadeIn('slow');
});
});
});
})
Here's the project I've setup in JSFiddle. And here's the form.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<form data-abide id="frmComment">
<div class="row">
<div class="large-12 medium-12 columns">
<div class="row" data-equalizer>
<div class="large-4 medium-4 columns">
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Name" name="name" required>
</label>
<small class="error">Name is required and must be a string.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Email" name="mailfrom" required pattern='.*#.*\..{3}|.*#.*\..{2}'>
</label>
<small class="error">An email address is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="g-recaptcha" data-sitekey="6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E"></div>
<noscript>
<div style="width: auto; height: 462px;">
<div style="width: auto; height: 422px; position: relative;">
<div style="width: auto; height: 422px; position: absolute;">
<iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E" frameborder="0" scrolling="no" >
</iframe>
</div>
</div>
<div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: ##f9f9f9; border: 1px solid ##c1c1c1; border-radius: 3px; height: 100px; width: 300px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 280px; height: 80px; border: 1px solid ##c1c1c1; margin: 10px; padding: 0px; resize: none;"></textarea>
</div>
</div>
<br /><br />
</noscript>
</div>
</div>
</div>
<div class="large-8 medium-8 columns">
<div class="row">
<div class="large-12 columns">
<textarea id="message" name="message" placeholder="Leave a comment...we love feedback!" rows="5" required></textarea>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<button type="submit" class="tiny right button">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="submitResponse"></div>
Okay, with some help, I managed to get the jQuery post to send the data to my proxyPost-KB.cfm page but it error out (505) when it hits that page. This is what I have in my proxyPost-KB.cfm page. None of the logs I setup in this CFM page is even get executed either.
<!---
Make the proxy HTTP request using. When we do this, try to pass along all of the CGI information that was made by the original AJAX request.
--->
<cflog text="CGI: #cgi#" type="Information" file="CGIparameters">
<cfhttp url="https://app.kb.com/api/head/comment.json" method="post" timeout="15" throwonerror="true">
<!---<cfhttpparam type="body" name="data"value="#serializeJSON(jsonString)#" />--->
<cfhttpparam type="url" name="_authbykey" value="56ec1f1232131c78636142d6">
<cfhttpparam type="url" name="project_id" value="55c4ffd123131c527e294fe6">
<!---<cfhttpparam type="url" name="article_id" value="#artID#">
<cfhttpparam type="url" name="content" value="#form.message#"/>
<cfhttpparam type="url" name="public_name" value="#form.name#"/>
<cfhttpparam type="url" name="public_email" value="#form.mailfrom#"/>--->
<cfhttpparam type="url" name="status" value="pending"/>
<!--- Pass along any URL values. --->
<cfloop item="strKey" collection="#URL#">
<!---<cfhttpparam type="url" name="public_name" value="#URL[strKey]#" />
<cfhttpparam type="url" name="public_email" value="#URL[strKey]#" />--->
<cflog text="URL: #URL[strKey]#" type="Information" file="CGIparameters">
</cfloop>
</cfhttp>
<!---
Get the content as a byte array (by converting it to binary,
we can echo back the appropriate length as well as use it in
the binary response stream.
--->
<cfset binResponse = ToBinary(ToBase64( objRequest.FileContent )) />
<!--- Echo back the response code. --->
<cfheader statuscode="#Val( objRequest.StatusCode )#" statustext="#ListRest( objRequest.StatusCode, ' ' )#" />
<!--- Echo back response legnth. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />
<!--- Echo back all response heaers. --->
<!---<cfloop item="strKey" collection="#objRequest.ResponseHeader#">
<!--- Check to see if this header is a simple value. --->
<cfif IsSimpleValue( objRequest.ResponseHeader[ strKey ] )>
<!--- Echo back header value. The cfheader tag generate the error "Complex object types cannot be converted to simple values"--->
<cfheader name="#strKey#" value="#objRequest.ResponseHeader[ strKey ]#" />
<cflog text="IsSimpleValue: #strKey#" type="Information" file="debugCFLoop">
</cfif>
</cfloop>--->--->
<!---
Echo back content with the appropriate mime type. By using
the Variable attribute, we will make sure that the content
stream is reset and ONLY the given response will be returned.
--->
<cfcontent type="#objRequest.MimeType#" variable="#binResponse#" />
Here's an example to do what you describe:
$("#frmComment").submit(function(event) {
event.preventDefault();
// Form has been submitted - now show your progress gif, eg:
// $('body').addClass('in-progress');
// or maybe:
// $('.spinner').show();
// etc - CSS can be whatever you want
// Cache $form, we'll use that selector more than once
var $form=$(this);
// Serialize all input from the form
var data=$form.serialize();
// Post it
$.post(
"your-proxy-url",
data,
function(response) {
// Success callback. Remove your progress gif, eg:
// $('body').removeClass('in-progress');
console.log(response); // show the proxy response on your console
// Now hide the form
$form.fadeOut('slow', function() {
// And show a result once it's gone
$(".result").html(response).fadeIn('slow');
});
}
);
});
I think you could use this code inside the $( "#frmComment" ).submit(function( event ) { function:
event.preventDefault();
var data = $('#frmComment').serialize(); //get all the data of form
var url = "yourUrl.php";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
The PHP 'yourUrl' will recive the form inputs (you could use var_dump($_POST); to see the structure.

Saving dynamically generated inputs grid with the same ng-model

I have these snippets of code :
$scope.createPack = function(informationsPack, informationsActivite) {
PackService.add(informationsPack, informationsActivite)
.then(function(res) {
$state.go('packs.list');
}, function(error) {
alert('error : ' + error);
})
};
<form name="packAddForm" id="packAddForm" class="form-horizontal">
<div ng-repeat="item in items">
Jour {{ item.jour }}
<div class="form-group">
<div>
<input type="text" id="nom_activite" class="form-control" placeholder="Nom Activité"
ng-model="informationsActivite.name_activity">
</div>
</div>
<div class="form-group">
<div>
<textarea name="description_activite" id="description_activite" cols="60"
rows="5" ng-model="informationsActivite.description_activity"></textarea>
</div>
</div>
</div>
</form>
<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="createPack(informationsPack, informationsActivite)">
Enregistrer</button>
What I'm trying basically to do is generating 1, 2 or 3 input based on what the user gave. And that is what the ng-repeat is doing. But the problem is when I submit the form how can I get all the values of the generated inputs. If it was just one input it would be ok. But for example if I have 2 informationsActivite.name_activity generated how can I get all datas. I really need help.
I think you need to do something like this
<div>
<textarea name="description_activite{{$index}}"
id="description_activite{{$index}}" cols="60" rows="5"
ng-model="informationsActivite.description_activity{{$index}}"></textarea>
</div>
to make these attribute values unique.
Side note- duplicate id attributes in a html document makes it invalid

Categories

Resources