I'm working on an MVC project. My requirement is to insert data to the database through a form. I've included the form inside a bootstrap modal.
My problem is, when I enter some data and click the save button, it inserts only null rows, not the entered values. Why does this happen? How do I make it to insert the real values instead of just passing nulls?
Here's the code for the modal.
#if (Model != null)
{
<div class="modal-content">
<!--modal header-->
<div class="modal-body">
<form id="actionForm">
<div class="form-group">
<label>Name</label>
<input type="text" name="Name" class="form-control" placeholder="Enter Accomodation Type Name...">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="Description" class="form-control" placeholder="Enter Accomodation Type Description..."></textarea>
</div>
</form>
<div id="errorDiv">
</div>
</div>
<div class="modal-footer">
<button type="button" id="actionButton" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
}
This is the script for the Save Changes button
<script>
$("#actionButton").click(function () {
$.ajax({
url: '#Url.Action("Action", "AccomodationTypes")',
type: "post",
data: $("actionForm").serialize()
})
.done(function (response) {
debugger;
if (response.Success) {
location.reload();
}
else {
$(".errorDiv").html(response.Message)
}
});
});
</script>
Since you are using $("actionForm").serialize() you have to bind the model to the form input controls:
<input type="text" asp-for"#Model.Name" name="Name" class="form-control"
placeholder="Enter Accomodation Type Name...">
// or you can try to replace asp-for by value="#model.Name"
<textarea asp-for="#Model.Description" name="Description" class="form-control"
placeholder="Enter Accomodation Type Description..."></textarea>
or if you using older versions of MVC you can try replace your input controls with this:
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
#Html.TextAreaFor(m => m.Description, new { #class = "form-control" })
And you have an javascript bug too. Replace
$("actionForm").serialize()
with
$("#actionForm").serialize()
or even better:
$("#actionForm").serializeArray()
Related
I am trying to add filepond framework for me image input but whenever I try to submit my data it gets
Error: ER_DATA_TOO_LONG: Data too long for column.
I tried to add the issue in their GitHub because I believe that it is because of the framework or I am missing any dependencies for the framework but they replied:
Hi, this is a MySQL question and not a question related to FilePond library, please ask it on Stack Overflow.
.ejs file
<form class="add-music-form" action="/save" method="post">
<div class="form-group filepond-custom-style">
<input type="file" name="filepond">
</div>
<div class="form-group margin-top">
<input type="text" class="form-control" placeholder="Title" id="title" name="title">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Band name" id="band_name" name="band_name">
</div>
<div class="form-group custom-file">
<input type="file" class="custom-file-input" id="customFile" name="audio">
<label class="custom-file-label" for="customFile">Select audio file</label>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a data-dismiss="modal" class="btn btn-default">Cancel</a>
</div>
</form>
app.js
app.post('/save',(req, res) => {
let data = {filepond: req.body.filepond, title: req.body.title, band_name: req.body.band_name, audio: req.body.audio};
let sql = "INSERT INTO music SET ?";
let query = connection.query(sql,data,(err, results) => {
if(err) throw err;
res.redirect('/');
});
});
I have an edit form as below which contains data in the input fields.
<ng-form #infoForm="ngForm" novalidate>
<div>
<label for="firstName">First Name :</label>
<input type="text"
class="form-control"
id="firstName"
name="firstName"
[(ngModel)]="in.firstName">
</div>
<div>
<label for="lastName">Last Name :</label>
<input type="text"
autocomplete="on"
class="form-control"
id="lastName"
name="lastName"
[(ngModel)]="in.lastName">
</div>
<button type="button" class="btn btn-primary" (click)="updateInfo(infoForm.value)">Update
</button>
</ng-form>
And I have the function in the component as below:
updateInfo(info: any) {
console.log(info);
}
This form return all the values (to the console) in the form when the Update button clicked, but I want to submit only the edited values instead of whole form. How could I implement it?
For this you can pass the form instead of its value to 'updateInfo' function and process it there. If user change the control value its state becomes 'dirty' from 'touched/pristine' and we can filter controls based on that.
Change in html:
<button type="button" class="btn btn-primary" (click)="updateInfo(infoForm)">Update
</button>
Change in *.ts file:
updateInfo(info: NgForm) {
const changedValues = Object.keys(info.controls)
.filter(key => info.controls[key].dirty === true)
.map(key => {
return { control: key, value: info.controls[key].value }
});
console.log(changedValues);
}
I am working on a project with Symfony 2.8. My main goal is to create a dynamic calendar based on Fullcalendar library.
I add my events called "dispos" (avalabilities in English) and "Rdvs" (appointments" in English) through a Json request and ajax. This works fine.
Now, I would like to transform availabilites into appointements (which are both considered as events in Fullcalendar).
E.g : When someone clicks on one availability a modal shows up, then the person fills the form in it and clicks "save" button.
When the "save" button is clicked, all informations entered in the form are sent and saved (through a Json request) into my Database and the appointment is taken
--> all events of the current should be reloaded through ajax, the event should be displayed with the title of the event entered (name of the patient) and the modal should contain all informations given/wrote before "save" action.
I tried to do it but my ajax is not working since events do not reload after saving everything else is working.
Anyway, I think I did it wrong somewhere. The code I will show you in my Controller returns a view because I didn't manage to return a response (+ I think routing or something is bad but don't know how to fix it...)
Any clue or advice woud be really appreciated :)
So here is my code :
TakeRdvAction in my controller :
/* ----------------- /
/ --- TAKE RDV ---- /
/ ----------------- */
public function takeRdvAction(){
$request = $this->get('request_stack')->getCurrentRequest();
parse_str($request->getContent(), $myArray);
/*$request->isXmlHttpRequest()*/
if (1) {
$dateHeureDispo=$myArray['heureDispo'];
$dateDispo= new \DateTime($dateHeureDispo);
$heureDispo = $dateDispo->format('H:i');
$dateDispo=$dateDispo->format('d-m-Y');
$civilite=$myArray['civilite'];
$nom=$myArray['inputNom'];
$prenom=$myArray['inputPrenom'];
$naissance=$myArray['birth'];
$email=$myArray['email'];
$tel=$myArray['tel'];
$telFixe=$myArray['telFixe'];
$adresse=$myArray['adresse'];
$cp=$myArray['cp'];
$ville=$myArray['ville'];
$pays=$myArray['pays'];
$medecin_traitant=$myArray['medecin_traitant'];
$ame=$myArray['ame'];
$cmu=$myArray['cmu'];
$takeRDv="http://connect.mysite.com/nameofapi2/takeappt?center=13&motive=238&prenom=".urlencode($prenom)."&nom=".urlencode($nom)."&email=".urlencode($email)."&birthdate=".$naissance."&address=".urlencode($adresse)."&cp=".$cp."&city=".urlencode($ville)."&country=".urlencode($pays)."&tel=".$tel."&titre=1&source=1&origine=1&daterdv=".$dateDispo."&time=".$heureDispo."&slot=1%E1%90%A7&civilite=".$civilite."&origin=smwh&referer=1";
$streamContext = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
]);
$json = file_get_contents($takeRDv, false, $streamContext);
$response = new jsonResponse();
$response->setContent($json);
return $this->indexAction();
}
else {
return new response("Ajax request failed");
}
}
If I put if ($request->isXmlHttpRequest()), the controller goes directly to "else" end returns "Ajax request failed"
Ajax.js file (It's the last ajax function we are talking about):
$(document).ready(function () {
/* TakeRdvs */
$("#monBouton").click(function(){
if (nom.value != "" && prenom.value != "" && email.value != "")
{
$.ajax({
url: "{{ path('takeRdv') }}",
method: 'POST',
data: {},
success: function(data) {
$("#calendarModal").modal('hide');
$("#calendarModal").on('hidden.bs.modal', function (e) {
$('#calendar').fullCalendar('refetchEvents');
});
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error: ' + errorThrown);
}
});
}
else if (nom.value == "")
{
alert('Veuillez renseigner le Nom');
return false;
}
else if (prenom.value == "")
{
alert('Veuillez renseigner le prénom');
return false;
}
else if (email.value == "")
{
alert("Veuillez renseigner l'adresse mail");
return false;
}
});
});
Other ajax functions work just fine, I made them after trying to take an appointment on an availability. When I implemented FosJsRouting, I thought it would be easier to try to make my takeRdvs action work. But the truth is, I don't know how to do it since it's a different action from the others and I am lost now :'(
My modal showing up when a event is clicked (got cut in several part sorry could not fix it):
×
close
<div class="form-group">
<div class="col-sm-12">
<h4 id="modalTitle" class="modal-title modify"></h4>
</div>
</div>
<div class="col-sm-4 form-group">
<label for="motif">
Motif de la consultation :
</label>
<select class="form-control" id="motif" data-placeholder="Choisissez un motif" style="width: 100%;" name="motif"> {# multiple data-max-options="1" #}
<option value="238"> Bilan de la vue</option>
<option value="Visite de controle"> Visite de contrôle</option>
<option value="Chirurgie réfractive"> Chirurgie réfractive</option>
<option value="Rééducation visuelle"> Rééducation visuelle</option>
<option value="Urgences"> Urgences</option>
</select>
</div>
<div class="form-group create">
<div class="col-sm-2">
<label class="control-label" for="civilite">Civilité</label>
<select class="custom-select" id="civilite" name="civilite">
<option value="Mme">Mme</option>
<option value="M">M.</option>
</select>
</div>
<div class="col-sm-5">
<label class="control-label" for="inputNom">Nom</label>
<input name="inputNom" type="text" class="form-control" id="inputNom" placeholder="Doe" required >
</div>
</div>
<div class="form-group">
<div class="col-sm-5 create">
<label class="control-label" for="inputPrenom">Prénom</label>
<input name="inputPrenom" type="text" class="form-control" id="inputPrenom" placeholder="Jane" required >
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" for="email">Email</label>
<input name="email" type="email" class="form-control" id="email" placeholder="jane.doe#example.com" required >
</div>
</div>
{# fin de la condition #}
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" for="naissance">Date de naissance</label>
<input name="birth" type="text" class="form-control" id="naissance" placeholder="01-01-2001" required>
</div>
<div class="col-sm-6">
<label class="control-label" for="tel">Mobile</label>
<input name="tel" type="tel" class="form-control" id="tel" placeholder="0607080910" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" for="telFixe">Téléphone fixe</label>
<input name="telFixe" type="tel" class="form-control" id="telFixe" placeholder="0101010101">
</div>
</div>
<div class="form-group">
<div class="col-sm-5">
<label class="control-label" for="adresse">Adresse</label>
<input name="adresse" type="text" class="form-control" id="adresse" placeholder="1 Bd de Strasbourg 83000 Toulon" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-3">
<label class="control-label" for="cp">Code postal</label>
<input name="cp" type="text" class="form-control" id="cp" placeholder="83000" required>
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="col-sm-4">
<label class="control-label" for="ville">Ville</label>
<input name="ville" type="text" class="form-control" id="ville" placeholder="Toulon" required>
</div>
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="col-sm-4">
<label class="control-label" for="pays">Pays</label>
<input name="pays" type="text" class="form-control" id="pays" placeholder="France" required>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" for="medecin_traitant">Médecin traitant</label>
<input name="medecin_traitant" type="text" class="form-control" id="medecin_traitant" placeholder="Dr Bicharzon" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" for="ame">
Bénéficiare de l'AME ?
</label>
<select class="form-control" name="ame" title="ame" id="ame" required>
<option value="oui">Oui</option>
<option value="non">Non</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" for="cmu">
Bénéficiare de la CMU ?
</label>
<select class="form-control" name="cmu" title="cmu" id="cmu" required>
<option value="oui">Oui</option>
<option value="non">Non</option>
</select>
</div>
</div>
<input title="heureDispo" class="visually-hidden form-control" name="heureDispo" type="text" id="heureDispo">
<div class="form-group boutonsModale col-sm-6">
<button type="button" class="btn btn-default btn-danger" data-dismiss="modal">Annuler</button>
<button type="submit" class="btn btn-primary" id="monBouton">Enregistrer</button>
</div>
</form>
</div>
{#{% endfor %}#}
<div class="modal-footer paddingTop">
{#<button type="button" class="btn btn-default btn-danger" data-dismiss="modal">Annuler</button>#}
{#<input type="submit" class="btn btn-primary">Enregistrer</input>#}
{#<button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>#}
</div>
</div>
</div>
</div>
</div>
Routing.yml :
Take RDV
take_rdv:
path: /prise-rdv
defaults: {_controller: RdvProBundle:Default:takeRdv}
methods: [POST]
options:
expose: true
I don't know how to change the route if I need to... + I would like the route no to show like the other routes I created but as it's coded now, it's shown...
I am junior junior as dev so I a sorry if my code is not clean :s
Thank you in advance for all the help you will provide.
It is huge. I'm not sure about your problem(s?) but if I understand :
First problem :
ajax is not working since events do not reload
If your #button is replaced in your page after your first call, the attached event is destroyed. Change your listener :
$("#monBouton").click(function(){
by
$('body').on('click', '#monBouton', function () { will solve the problem.
Second problem :
If I put if ($request->isXmlHttpRequest()), the controller goes directly to "else"
I suggest to pass $request as argument of your action and just put your condition within an if statement :
public function takeRdvAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
[...]
}
}
Thirdly :
To use FosJsRouting, you exposed your route in your yaml. That's good. To use it in javascript, you have to include the given script in your base.html.twig and use Routing.generate just as defined in the doc :
$.ajax({
url: Routing.generate('take_rdv', {/* $(yourform).serialize() ?*/}),
method: 'POST',
data: {},
success: function(data) {
$("#calendarModal").modal('hide');
$("#calendarModal").on('hidden.bs.modal', function (e) {
$('#calendar').fullCalendar('refetchEvents');
});
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error: ' + errorThrown);
}
});
Update
With my suggestions, you've to change how you use $request in your action :
$myArray = $request->request->all();
$civilite=$myArray['civilite'];
[...and so on...]
Bonus : Symfony is a powerfull framework. I suggest you to learn about using this framework and especially, in your case, about Forms
enjoy :)
UPDATE 2
if ($request->isXmlHttpRequest()) { is never true cause you are not doing an ajax call. I just see that, but your button is of type submit then, your browser send a basic HTTP request.
Add this to your js code :
$('body').on('click', '#monBouton', function (event) {
event.preventDefault();
[...$.ajax blablabla]
});
I'm trying to input a username and password into the input fields and send them to the API URL to authenticate the user and return data. I can provide hardcoded credentials to the URL and successfully login. But what I need is to able to input values in the Web interface dynamically and perform the login.
I have no idea how to bind input values into the URL and how the format should be written. Please help with this.
My controller with hard-coded username and password:
var login = angular.module('login', []);
login.controller('loginController', ['$scope','$http','$location',function($scope, $http) {
$scope.loginauth = function(username,password)
{
$http({
method : 'POST',
url : 'http://televisionarybackendservices.azurewebsites.net/auth/login?username=Evangeli&password=1234',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data)
$scope.userData = data;
});
};
enter code here}]);
My html modal to log in;
<div id="loginModal" class="modal fade" role="dialog" ng-controller="loginController">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<form class="form" action="" method="POST" enctype="multipart/form-data" role="form">
<div class="form-group">
<label for="ue">Username</label>
<input type="text" class="form-control" id="ue" placeholder="" ng-model="username">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" class="form-control" id="pwd" placeholder="" ng-model="password">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" ng-click="loginauth(username,password)">Login</button>
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
<div ng-repeat="data in userData">
{{data.username}}<br />
{{data.created_at}}
</div>
</div>
</div>
</div>
I need to enter username and password dynamically and not supply hard-coded values. Thanks in advance.
Well i got the answer.This is for anyone who need help.
var login = angular.module('login', []);
login.controller('loginController', ['$scope','$http','$location',function($scope, $http) {
$scope.loginauth = function(username,password)
{
$http({
method : 'POST',
url : 'http://televisionarybackendservices.azurewebsites.net/auth/login',
data: jQuery.param({
username: $scope.username,
password: $scope.password
}),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data)
$scope.userData = data;
});
};
}]);
Below form is for modal window I have two fields if i select the values and without saving or even after save if i open modal window again i see all the required field messages, How can i reset the validation messages every time i open the modal window ?
main.html
<form name="addChallengeForm" id="addChallengeForm" novalidate ng-controller="challengesCtrl" class="border-box-sizing">
<div class="modalForm">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="originatingGroup" class="required col-md-4">Originating group:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="originatingGroup"
k-option-label="'Select'" ng-model-options="{updateOn: 'blur'}"
ng-model="challengesDTO.originatingGrpLkupCode"
k-data-source="challengeGroupOptions"
id="originatingGroup" required>
</select>
<p class="text-danger" ng-show="addChallengeForm.originatingGroup.$touched && addChallengeForm.originatingGroup.$error.required">Originating group is required</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="challangeDes" class="required col-md-4">Description of challenge:</label>
<div class="col-md-8">
<textarea rows="4" class="form-control"
name="challangeDes" id="challangeDes"
ng-model="challengesDTO.challengeDescription" required
placeholder="Description of challenge" ng-model-options="{updateOn: 'blur'}">
</textarea>
<p class="text-danger" ng-show="addChallengeForm.challangeDes.$touched && addChallengeForm.challangeDes.$error.required">Description of challenge is required</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addChallengeForm.$invalid" ng-click="submit()">Save</button>
</div>
</form>
mainCtrl.js
$scope.addChallenge = function (opCheckList,checklistSessionKey) {
challengesGridConfig.challengemodalWinConfig.title = 'Add challenge';
$scope.viewChallengeWin.setOptions(challengesGridConfig.challengemodalWinConfig);
$scope.$broadcast('addChallenge', $scope.riskAssessmentDTO.riskAssessmentKey,opCheckList,checklistSessionKey);
};
childCtrl.js
$scope.$on('addChallenge', function (s,id,opCheckList,checklistSessionKey){
$scope.viewChallengeWin.open().center();
$scope.editMode = false;
$scope.clearFields = clearForm();
});
var clearForm = function(){
$scope.challengesDTO = {
themesKyList: null
};
$scope.challengeGroupOptions = kendoCustomDataSource.getDropDownDataSource('RA_ASES_CHLNG_GRP');
$scope.challengThemesDataSource = kendoCustomDataSource.getDropDownDataSource('RA_CHLNG_THEME');
$scope.challengOutComeOptions = kendoCustomDataSource.getDropDownDataSource('RA_CHLNG_OUTCOME');
};
I think, when you are opening the modal you should reset conditions you're using in ng-show (for errors) to default. You're checking if input was touched, why don't you set it untouched when opening modal?
$scope.addChallengeForm.originatingGroup.$setUntouched();
$scope.addChallengeForm.challangeDes.$setUntouched();