How to submit multiple forms on one route using handlebars - html

I'm having trouble with posting information on two forms using handlebars. I just started learning it so I'm not to comfortable with it yet. Basically Im trying to display information from two tables in my database onto two forms by searching for the project id and returning that information. I have it working for the first form. Whenever I search the project ID, the relevant information is returned. But when I search for the project ID on the next form, it populates data on the first form and completely ignores the second form. Ill post all the code I think is relevant to this question.
This is the controller and the route that handles the first form
findOne: async (req, res) => {
const { project_id } = req.body
const metadata = await Prjt_metadata.findOne({
where: {
project_id
}
});
return res.render('allForms', {
metadata
})
}
}
router.post('/find', metadataController.findOne)
This is the controller and the route that handles the second form
getOneCostsHours: async (req, res) => {
try {
const { project_id } = req.body
const costsHours = await Prjt_costs_hours.findOne({
where: {
project_id
}
});
return res.render('allForms', {
costsHours
})
} catch (error) {
console.error(error.message);
return res.status(500).json(error);
}
}
router.post('/find', costsHoursController.getOneCostsHours);
This is the html code for the first form
<form action='/find' method='POST'>
<section class="row">
<div class="col-md-4">
<div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Project ID:</span>
</div>
<input id="disabled" name="project_id" type="text" class="form-control">
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Building:</label>
<select disabled name="building" class="form-select" id="inputGroupSelect01">
{{#with metadata}}
<option selected>{{building}}</option>
{{/with}}
</select>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Measure Type:</label>
<select disabled name="measure_type" class="form-select" id="inputGroupSelect01">
{{#with metadata}}
<option selected>{{measure_type}}</option>
{{/with}}
</select>
</div>
<div class="text-end">
<button id="search" type="submit" style="background-color: #bf5700;"
class="btn text-light btn-warning mt-3">Search</button>
</div>
</form>
This is the html code for the second form
<form action='/find' method="POST">
<div class="card border-secondary text-light mb-3" style="background-color: #333f48;">
<h5 class="card-header">Costs & Hours</h5>
<div class="card-body">
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">Project ID:</span>
<input name="project_id" type="text" class="form-control"
aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Implementation or
Annual:</label>
<select disabled name="imp_or_ann" class="form-select" id="inputGroupSelect01">
{{#with costsHours}}
<option>{{imp_or_ann}}</option>
{{/with}}
</select>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Category:</label>
<select disabled name="category" class="form-select" id="inputGroupSelect01">
{{#with costsHours}}
<option>{{category}}</option>
{{/with}}
</select>
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">Costs: $</span>
{{#with costsHours}}
<input disabled value={{cost}} name="cost" type="text" class="form-control" aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default">
{{/with}}
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">Hours:</span>
{{#with costsHours}}
<input disabled value={{hours}} name="hours" type="text" class="form-control" aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default">
{{/with}}
</div>
</div>
<button type="submit" style="background-color: #bf5700;"
class="btn btn-warning text-light">Search</button>
</div>
</form>
The value for project_id comes from the input with name "project_id" on both forms. Like I said above, the first form works fine. It gets the relevant info based on the project_id. But When I search on the second form, it gets ignored and the data from the first form gets posted again.
Hopefully my question makes sense. I can explain it better if anyone needs me to.
Thanks for any help in advance! I'm hoping to learn more about handlebars in the future

I figured it out by just combining the two controllers into a separate controller and route
New controller and route
const { Prjt_metadata, Prjt_costs_hours } = require('../models');
module.exports = {
findOne: async (req, res) => {
try {
const { project_id } = req.body
const metadata = await Prjt_metadata.findOne({
where: {
project_id
}
});
const costsHours = await Prjt_costs_hours.findOne({
where: {
project_id
}
});
return res.render('allForms', {
metadata,
costsHours,
})
} catch (error) {
console.error(error.message);
return res.status(500).json(error);
}
}
}
const router = require('express').Router();
const getOneByIdController = require('../controllers/getDataById');
router.post('/find', getOneByIdController.findOne)
module.exports = router

Related

How can I pass a select HTML element as a parameter in a onSubmit form call?

I am trying to pass the html elements of a form through the submit function as parameters. I can get correctly the nameInput element with flag #nameInput, but the select element (#skillSelect) is throwing this error:
- error TS2339: Property 'skillSelect' does not exist on type 'MemberFilterComponent'.
Here is my form template. How can I pass the select element to component as I did with the input text?:
<form
[formGroup]="filterMemberForm"
(ngSubmit)="onSubmit(nameInput, skillSelect)"
>
<div class="form-row">
<div class="col-md-3">
<label class="font-weight-bold"
>Name
<input
ngDefaultControl
type="text"
class="form-control"
label="'Name'"
formControlName="name"
placeholder=" Ex: Maria Novillo"
required
id="name"
#nameInput
(change)="mapChipValue(nameInput)"
/></label>
</div>
<div class="col-md-3" *ngIf="skills.length !== 0">
<label class="font-weight-bold">Skills:</label>
<select
id="skillId"
class="form-control"
formControlName="skillId"
#skillSelect
(change)="mapChipValue(skillSelect)"
>
<option value="">-- Select skills --</option>
<option *ngFor="let skill of skills" [value]="skill.idSkill">
{{ skill.skill }}
</option>
</select>
</div>
<div class="form-row">
<div class="col-md-3 mt-5">
<button type="submit" class="btn btn-primary">Apply</button>
</div>
</div>
</form>
In the html file:
<select class='select-option'
#mySelect
(change)='onOptionsSelected(mySelect.value)'>
<option class='option'
*ngFor='let option of dropDownData'
[value]="option.seo_val">{{option.text_val}}</option>
</select>
In the ts file:
onOptionsSelected(value:string){
console.log("the selected value is " + value);
}
why you need pass the "html element"? in filterMemberForm.value you has an object with the values. Really your form should be
<form
[formGroup]="filterMemberForm"
(ngSubmit)="onSubmit(filterMemberForm)"
>
onSubmit(form:FromGroup)
{
if (form.valid)
console.log(form.value)
else
form.markAllAsTouched()
}
if you need the selectOption name always can makes
onSubmit(form:FromGroup)
{
if (form.valid)
{
//if is not multiple select
const selectedItem=this.skills.find(x=>x.idSkill==form.value.skillId)
console.log(form.value,selectedItem)
//if is multiple select
const selectedItems=this.skills.filter(
x=>form.value.skillId.indexOf(x.idSkill)>=0)
console.log(form.value,selectedItems)
}
else
form.markAllAsTouched()
}

how to get filename value from filepond?

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('/');
});
});

Angular6 | Disable form validation for hidden fields

Background
I have a form where I give the user the option to specify either a quick time-frame or a detailed one (with a specific start/end time) - i.e. the user has the option to fill only one out of the two
The type of option that they wish to choose can be toggled with the click of a button. These buttons just toggle the hidden parameter on the specified divs
Issue
My problem here is that both of these fields (all 3 technically as start/end time are 2 separate form group divs under one generalized div) are required only if they are not hidden - I am not sure how this can be achieved with Angular 4/5/6 (using 6 here)
My invalid form trigger always goes off as the hidden field is also required
My Form
<div class="card-block">
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<div class="form-group">
<label for="transactionType"> Request Type </label>
<select
class="form-control"
[(ngModel)]=data.transactionType
name ="transactionType"
#transactionType="ngModel"
required>
<option value="something1Count">Something1</option>
<option value="something2Count">Something2</option>
</select>
<div *ngIf="transactionType.errors?.required && transactionType.touched" class="alert alert-danger">
Please select a transaction type
</div>
</div>
<br>
<div class="form-group">
<label>Timeframe Type</label>
<br>
<button type="button" class="btn btn-light" (click)="quickTimeframe = false; detailedTimeframe = true;" ng-selected="!quickTimeFrame"> Quick </button>
<button type="button" class="btn btn-light" (click)="detailedTimeframe = false; quickTimeframe = true;" ng-selected="!detailedTimeframe"> Detailed </button>
</div>
<div class="form-group" [hidden]="quickTimeframe">
<label for="timeframe">Timeframe</label>
<select
class="form-control"
[(ngModel)]=data.timeframe
name ="timeframe"
#timeframe="ngModel"
required>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
<option value="60">60 Minutes</option>
</select>
<div *ngIf=" !quickTimeframe && timeframe.errors?.required && timeframe.touched" class="alert alert-danger">
Please select a timeframe
</div>
</div>
<div class="detailed" [hidden]="detailedTimeframe">
<div class="form-group">
<label for="startTime">Start of Time Range</label>
<input
type="datetime-local"
class="form-control"
[(ngModel)]="data.startTime"
#startTime="ngModel"
name="startTime"
required
>
<div *ngIf="!detailedTimeframe && startTime.errors?.required && startTime.touched" class="alert alert-danger">
Please select a start-time
</div>
</div>
<div class="form-group">
<label for="endTime">End of Time Range</label>
<input
type="datetime-local"
class="form-control"
[(ngModel)]="data.endTime"
#endTime="ngModel"
name="endTime"
required
>
<div *ngIf="!detailedTimeframe && endTime.errors?.required && endTime.touched" class="alert alert-danger">
Please select an end-time
</div>
</div>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Submit">
</form>
</div>
</div>
TS File
import { Component, OnInit } from '#angular/core';
import { Inputs } from '../../models/Inputs';
import { Router } from '#angular/router';
import {FlashMessagesService} from 'angular2-flash-messages';
#Component({
selector: 'app-main-form',
templateUrl: './main-form.component.html',
styleUrls: ['./main-form.component.css']
})
export class MainFormComponent implements OnInit {
data:Inputs = {
transactionType:'',
timeframe:null,
startTime:'',
endTime:''
};
quickTimeframe:boolean=true;
detailedTimeframe:boolean=true;
buttonResult:any;
constructor(public router:Router, public flashMessagesService:FlashMessagesService) {
}
ngOnInit() {
}
onSubmit({value, valid}:{value:Inputs, valid:boolean}){
console.log("Quick Time Flag: " +this.quickTimeframe);
console.log("Detailed Time Flag: " +this.detailedTimeframe);
if (valid && !this.quickTimeframe){
console.log("Form is valid");
//Stuff should happen
console.log(value);
} else if (valid && !this.detailedTimeframe) {
console.log(this.data.startTime);
//Other stuff should happen
}
else {
console.log("Form is not valid");
this.flashMessagesService.show('Choose Valid Parameters', {cssClass:'alert-danger', timeout: 4000});
}
}
radioClick() {
console.log(this.buttonResult);
}
}
Report Inputs Interface (for completion's sake)
export interface Inputs {
transactionType?:string;
timeframe?:number;
startTime?:string;
endTime?:string;
}
*ngIf did the trick
Using ngIf instead of hidden ensure that the elements do not exist within the form in my scenario

Inserting form data into MySQL database when using NodeJS Express

For a school project I need to insert data from a html form into my database. The problem is, I never worked with NodeJS, Express, Handlebars or JavaScript before and I cant seem to figure out how it works, I currently have this form in my .hbs file
<div class="row">
<form action="" method="post" class="col s12">
<div class="row">
<div class="col s3 offset-s1">
<label>Sensor Type</label><br>
<label>
<input id="combo" class="with-gap" name="sensorType" type="radio"/>
<span>Temperature & Humidity</span>
</label><br>
<label>
<input id="temp" class="with-gap" name="sensorType" type="radio"/>
<span>Temperature</span>
</label><br>
<label>
<input id="humid" class="with-gap" name="sensorType" type="radio"/>
<span>Humidity</span>
</label>
</div>
</div>
<div class="row">
<div class="input-field col s3 offset-s1">
<select id="sensorForest">
<option value="" disabled selected>Choose your forest</option>
<optgroup label="The Netherlands">
<option value="streekbos">Streekbos Bovenkarspel</option>
</optgroup>
<optgroup label="United States of America">
<option value="losAngeles">Los Angeles National Forest</option>
</optgroup>
</select>
<label>Forest</label>
</div>
<div class="input-field col s3">
<textarea id="textarea2" class="materialize-textarea" data-length="50"></textarea>
<label for="textarea2">Enter sensor Location</label>
</div>
</div>
<div class="row">
<div class="input-field col s6 offset-s1">
<div class="input-field col s6">
<input id="latitude" type="text" class="validate">
<label for="latitude">Latitude</label>
</div>
<div class="input-field col s6">
<input id="longitude" type="text" class="validate">
<label for="longitude">Longitude</label>
</div>
</div>
</div>
<div>
<div class="row">
<div class="col s12 offset-s1">
<button class="btn waves-effect waves-light" id="submit">Submit
<i class="material-icons right">send</i>
</button>
</div>
</div>
</div>
</form>
</div>
Ive also managed to extract the values of the fields in the form using the following script, but I dont think I can use this since I have to use NodeJS
<script>
var submit = document.getElementById("submit");
submit.onclick = function () {
//var sensorType = document.getElementById("sensorType").value;
var sensorForest = document.getElementById("sensorForest").value;
var sensorLocation = document.getElementById("textarea2").value;
var latitude = document.getElementById("latitude").value;
var longitude = document.getElementById("longitude").value;
console.log(sensorForest, sensorLocation, latitude, longitude);
};
</script>
Does anyone know how I'm supposed to send the data to my database or know a good tutorial that explains me how to do it?
Thank you
To connect your NodeJS/ExpressJS application to a database (mongodb, mysql,...) you need an ORM library. For your case i suggest Sequelize. All infos at http://docs.sequelizejs.com/
no you don't need an ORM library. You can just use mysql package from npm
Well before you save anything to a database, you have to get it to your server. I recommend using built-in fetch or if you want better browser support use axios, request-promise or superagent. All of these packages can be found on npm
Client
Underneath your click handler
fetch('http://localhost:3000/sensors', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
sensorForest,
sensorLocation,
latitude,
longitude,
})
})
.then(function (results) {
return results.json()
})
.then(function (results) {
console.log('got results', results)
})
.catch(function (ex) {
console.error(ex)
})
Dependencies
npm init -y && npm i --save express body-parser
Server
const express = require('express')
const { json } = require('body-parser')
const app = express()
const PORT = process.env.PORT || 3000
app.post('/sensors', json(), (req, res, next) => {
const body = req.body
// ...save `body` to database
// use mysql, sequelize, or knex
res.send(body)
})
app.listen(PORT, () => console.info(`Server listening on port "${PORT}"`))

Fullcalendar on Symfony add/modify events through modal and send back Json file to Database

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]
});