Triggering bootstrap modal on form submit and not on click - javascript

I want to trigger a bootstrap modal on submit and not on click as it is programmed to do by default.
This is my form and the button that triggers the modal :
<form name="signup-form" action="http://formspree.io/davidgeismar#wetennis.fr" id="conversion_form" method="POST">
<input id="email-input" class="signup-input" type="email" name="email_address" value="" placeholder="Laisse ton mail et reçois le coupon..." title="Please enter a valid email address." required>
<button type="submit" class="submit-btn"data-toggle="modal" data-target="#myModal">GO</button>
</form>
and this is the modal :
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
I tried this as was suggested in a post :
$("#myModal").on("show.bs.modal", function(e){
e.stopPropagation();
})
but this is not working.
What I should do is only trigger the modal when the form is actually submitted. This is after this bunch of JS code :
$("#conversion_form").on("submit", function(e){
e.preventDefault();
var $this = $(this);
var email = $('#email-input').val();
$.ajax({
url: $this.attr('action'), // Le nom du fichier indiqué dans le formulaire
method:"POST",
dataType: "json", // La méthode indiquée dans le formulaire (get ou post)
data: {message: email}, // Je sérialise les données (j'envoie toutes les valeurs présentes dans le formulaire)
success: function(data, textStatus, xhr) {
if(xhr.status==200)
alert('Nous vous tiendrons au courant de nos dernières actu ! \n Wefoot');
$('#email-input').val('');
// $('#myModal').popover('show');
}
});
})

You need to remove data-toggle="modal" data-target="#myModal" and trigger your modal manually, you could use this in your code
First initialize your modal to false so that it doesn't open up
$('#myModal').modal({ show: false})`
in submit method write below code
$('#myModal').modal('show');

If you want to show your modal after the form has completed the submit process you could just add this code in your success function:
$("#conversion_form").on("submit", function(e){
e.preventDefault();
var $this = $(this);
var email = $('#email-input').val();
$.ajax({
url: $this.attr('action'), // Le nom du fichier indiqué dans le formulaire
method:"POST",
dataType: "json", // La méthode indiquée dans le formulaire (get ou post)
data: {message: email}, // Je sérialise les données (j'envoie toutes les valeurs présentes dans le formulaire)
success: function(data, textStatus, xhr) {
if(xhr.status==200)
alert('Nous vous tiendrons au courant de nos dernières actu ! \n Wefoot');
$('#email-input').val('');
$('#myModal').modal('show'); // Add this and it will open the modal
}
});
});
Or if you want to do it before the form submits then just add
$('#myModal').modal('show');
before the ajax call. You can find more info here: https://stackoverflow.com/a/13183713/2911633

Related

AJAX values undefined with Symfony

I actually try to make an custom authentication using AJAX and Symfony but I have a problem that I can't even identify.
It seems that the AJAX part doesn't find the route because my browser console can't "recognize" my route script. I tried to identify AJAX data compared to input fields data and the problem is that AJAX returns undefined values. I'll put the different parts of my code below :
Twig modal with AJAX script :
<div class="modal fade" tabindex="-1" role="dialog" id="loginModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Connexion</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body" align="center">
<form action="#" method="POST">
<label for="pseudoMail">Pseudo ou e-mail : </label>
<input type="text" id="pseudoMail" placeholder="Pseudo ou e-mail" name="pseudoMail" required><br>
<label for="mdp">Mot de passe : </label>
<input type="password" id="mdp" placeholder="Mot de passe" name="mdp" required><br>
<input type="submit" class="btn btn-primary" id="login" value="Se connecter" />
</form>
</div>
</div>
</div>
</div>
<script src="{{ asset('js/jquery-3.5.1.min.js') }}"></script>
<script>
$(document).ready(function () {
$("#login").click(function()
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '{{ path('checkLogin') }}',
data: {
pseudo: $("input#pseudoMail").val(),//TODO Remplir l'Ajax de façon à ce que les données soient reconnues
motdepasse: $("input#mdp").val()
},
dataType: 'json',
success: function(data)
{
if(data.pseudo !== "" && data.motdepasse !== "")//TODO Modifier la condition et jouer les sons correspondants (dossier sfx)
{
setTimeout(alert("Vous êtes connecté !"), 5000);
var sound = document.createElement('audio');
sound.setAttribute('src', 'https://themushroomkingdom.net/sounds/wav/smb/smb_1-up.wav');
sound.play();
}
else
{
alert("Les identifiants ne correspondent pas. Veuillez réessayer.");
var sound = document.createElement('audio');
sound.setAttribute('src', 'https://themushroomkingdom.net/sounds/wav/smb/smb_fireworks.wav');
sound.play();
}
},
error: function(data)
{
console.log("Pseudo : " + data.pseudo);
console.log("Mot de passe : " + data.motdepasse);
console.log("Pseudo sans data : " + $('input#pseudoMail').val());
console.log("Mot de passe sans data : " + $('input#mdp').val());
console.log(data);
alert("Erreur détectée ! " + data);
}
});
});
});
</script>
The PHP script :
/**
* #Route("/checkLogin", name="checkLogin")
*/
public function checkLogin(Request $request, SessionInterface $session)//TODO vérifier les connexions pour mesures de sécurité ?
{
$pseudoMail = $request->request->get('pseudoMail');
$motdepasse = $request->request->get('mdp');
$repo = $this->getDoctrine()->getRepository(Utilisateur::class);
$pseudoDB = $repo->findOneBy(["pseudo" => $pseudoMail]);
$mailDB = $repo->findOneBy(["email" => $pseudoMail]);
$motdepasseDB = $repo->findOneBy(["motDePasse" => $motdepasse]);
if (($pseudoDB && $motdepasseDB) || ($mailDB && $motdepasseDB))
{
$session->set('login', true);
/*return $this->render('boutique/index.html.twig', [
'controller_name' => 'BoutiqueController',
]);*/
var_dump($pseudoMail . "-" . $motdepasse);
return new JsonResponse(array('pseudo' => $pseudoMail, 'motDePasse' => $motdepasse));
}
else
{
$session->set('login', false);
//$this->addFlash('flash', "Login incorrect. Veuillez réessayer.");
/*return $this->render('accueil/index.html.twig', [
'controller_name' => 'AccueilController',
]);*/
return new Response("Problème !");
}
}
As charlietfl said, you get different keys between your AJAX code and your PHP code. They should equal.
data: {
pseudo: $("input#pseudoMail").val(),
motdepasse: $("input#mdp").val()
},
In your AJAX request, keys are pseudo and motdepasse. So, in your PHP code, you should use those keys like that:
$pseudoMail = $request->request->get('pseudo');
$motdepasse = $request->request->get('motdepasse');

How to get a ID in a modal coming by dataTable?

My question is, I'm posting an ID into a modal, but when I click in a datepicker inside modal, it gives me as an undefined value, it seems that I'm losing the ID somewhere, could you help me? Here is my code:
Here is my modal HTML:
<div class="modal fade" id="modalUpdatePeriodico" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered " role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Prontuário médico</h4>
<!-- para pegar o id do meu campo -->
<input type="hidden" id="hiddenIdPeriodic"/>
</div>
<div class="modal-body">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- Inicio do Formulario de Pesquisa -->
<form id="formUpdatePeriodico" enctype="multipart/form-data" action="#" method="POST">
<!-- Form Data e Qtde dias -->
<div class="form-row">
<div class="form-group col-md-6">
<label for="dateExam">Data da Realização</label>
<input type="text" class="form-control datepicker-calendar" id="dateExam" name="dateExam">
</div>
<div class="form-group col-md-6">
<label for="statusExam">Status</label>
<select class="form-control select2" id="statusExam" name="statusExam">
<option value="1">Inapto</option>
<option value="2">Apto</option>
</select>
</div>
</div>
</form>
<!-- Fim do Formulario de Pesquisa -->
</div>
<!--/.col (right) -->
</div>
<!-- /.row -->
</div>
<div class="modal-footer">
<button
type="button"
id="btnSavePeriodic"
class="btn btn-success"
data-dismiss="modal"
onclick="saveEmpRestrictions('periodics', inputMatriculaAtes, dateExam, statusExam, hiddenIdPeriodic, examType);">
Salvar
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
Here is my DataTable JS code:
function tbPeriodic() {
// Definição do id da tabela como um dataTable
$("#tbPeriodico").DataTable({
"ajax": "webservices/ws_medicalRecord/tables/tb_medicalRecords.php?action=per&matriculaOp=" + <?php echo $matricula; ?>,
sorting: false,
"columns":
[
{ "data": "id" ,
render: function(data, type, row) { // Função para link de download dos arquivos que foram "upados" no formulário.
data = '' + row.id + '';
return data;
}
},
{ "data": "ult_exame" },
{ "data": "tipo_exame" },
{ "data": "status_exame" },
{ "data": "prox_exame" }
]
});
}
Here is my function to post my id into a input hidden:
$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
console.log(id);
var modal = $(this);
modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
Here is my datepicker function:
$('.datepicker-calendar').datepicker({
autoclose: true
});
So, when I input a date from my datepicker the console shows me undefined, could you help me?
Thanks a lot!
I think you are confused here and there are 2 things happening. Or I should say there is one thing happening and the other step is missing. I am going to try and clarify this for you.
#1
The undefined is happening because you are not getting the value of id correctly. Add a class clickme to your dataTable <a> like below and get rid of the modal call.
dataTable
data = '<a class="clickme" href="#" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';
Then get rid of
$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
console.log(id);
var modal = $(this);
modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
and change it to
$(document).on('click', '.clickme', function() {
var id = $(this).data('id');
$('#modalUpdatePeriodico').modal('show');
$('#modalUpdatePeriodico').find('#hiddenIdPeriodic').val(id);
console.log(id);
})
#2
The date thing is a different event so add this to get the date
$('.datepicker-calendar').datepicker({
autoclose: true,
onSelect: function(date) {
console.log(date)
}
})

AngularJS/PHP form inside ng-repeat : how to get specific data

I have a form which is composed of an ng-repeat (for each demand).
The user will be able to edit the "date réalisation" or the "motif refus" inside this ng-repeat, and will click on the button submit "Valider la modification", still inside this ng-repeat (to edit the demand in demands).
Here is the code :
<div class="jumbotron" ng-controller="gestDemInstallController">
<h1 class="text-center">{{ soustitre }}</h1>
<p>{{presentation}}</p>
<!--une ligne pour chaque demande
utilisation de getDataDemandesInstall.php
et de getDataDemandesInstallApplis.php
-->
<form>
{{ reussite }}<!-- indique un msg au clic du gestionnaire -->
<br><!-- on affiche chaque demande d'installation -->
<div ng-repeat="dem in demandesInstallations" class="tableau">
<br>
<label>ID :</label>
{{dem.id}}
<br>
<label>Ordinateur :</label>
{{dem.nomPC}}
<br>
<label>Date demande :</label>
{{dem.dateDemande}}
<br>
<label>Date réalisation :</label>
<input ng-model="date_real" type="date" value="{{dem.dateRealisation}}" class="form-control input-normal bouton">
Date enregistrée: {{dem.dateRealisation}}
<br><br>
<label>Motif refus :</label>
<input ng-model="motif_refus" type="text" value="{{dem.motifRefus}}" class="form-control input-normal bouton">
<br>
<label>Unité :</label>
{{dem.unite}}
<br>
<label>Demandeur :</label>
{{dem.demandeur}}
<br>
<!--boucle ng-repeat affichant chaque appli et profil choisi-->
<div ng-repeat="a in demandesInstallApplis">
<label><i>Applications demandées</i></label><br>
<label>Nom application :</label>
{{a.nom}}
<br>
<label>Profil demandé :</label>
{{}}
</div><!--fin ligne les applications-->
<input ng-model="btn{{dem.id}}" ng-click="checkGestDemInstall()" type="button" value="Valider la modification" class="form-control">
</div><!--fin de la demande, fin du ng-repeat-->
</form>
And here is the Controller (AngularJS)
//----RECUPERATION DES DONNEES : METHODE POST---------//
//----------------------------------------------------//
$scope.checkGestDemInstall = function(){
//on valide les données entrées
//on peut ensuite les envoyer au script PHP
//en utilisant la méthode HTTP Post
var error=0;
/*---- Le mot de passe est vérifié --*/
//si pas d'erreur (ni d'erreur mdp ni d'erreur id/mail)
if (error === 0) {
//on lance la méthode POST de la requête HTTP
var request = $http({
method: "post",
url: "/sio2/projets/gedeon_php/pages/postGestDemInstall.php",
data: {
//celui qui a été cliqué
date_real: $scope.date_real,
motif_refus: $scope.motif_refus
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Check whether the HTTP Request is Successfull or not. */
request.success(function (data) {
$scope.reussite = "Données bien envoyées : "+data +" (information réceptionnée de PHP)";
});
}
else {
$scope.reussite = "Vous avez mal rempli le formulaire. Erreur de type : " + error;
}
}; //fin fonction checkGestDemInstall()
As you can see in my Controller, I would like to get my data, I mean the dem.date_real and the dem.motif_refus, whereas I have the same ng-model for each input... Indeed I have several inputs (one by ng-repeat) and I don't really know how to get data from the "date_real" edited and the "motif refus" edited.
Thanks for any advices !
////////////////////
Thanks to your advice I now have these codes but still with some errors :
ERROR 1 : $parse:syntax
ERROR 2 : ngRepeat:dupes
here inside my ng-repeat dem in demands :
<label>Date réalisation :</label>
<input ng-model="dem.dateRealisation" type="text" value="{{dem.dateRealisation}}" class="form-control input-normal bouton">
Date enregistrée: {{dem.dateRealisation}}
<br><br>
<label>Motif refus :</label>
<input ng-model="dem.motifRefus" type="text" value="{{dem.motifRefus}}" class="form-control input-normal bouton">
and here in my Controller :
data: {
//celui qui a été cliqué
date_real: $scope.dateRealisation, //= new Date(dateRealisation),//error ngModel:datefmt
motif_refus: $scope.motifRefus
},
And then here to POST my data, I want to check by echoing it in PHP as I usually do before doing an insert...
include('../bdd/conn.php');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$date_real = $request->dateRealisation;
#$motif_refus = $request->motifRefus;
echo 'date real : '. $date_real . ' motif refus : '. $motif_refus;
I like everything to be understandable so I made a small scheme to explain :
If I understand correctly, change your ng-model to dem.dateRealisation and dem.motifRefus instead of date_real and motif_refus. If you use the variables defined on the scope then for every demand that you change the dates for it will update these variables, only ever returning one value for each.
If you want the data you are sending in your Post request to contain the dates for every demand, then you'll have to send a different object. You could send demandesInstallations and then change how this data object is handled

Javascript : changing text into paragraph tags

I'm trying to change the text inside a paragraph tag like so :
<script>
function select()
{
if (document.getElementById("lan").value=="Français")
{
document.getElementById("txt1").text="Veuillez entrer votre adresse mail et cliquer sur le bouton ci-dessous.";
document.getElementById("txt2").text="Consultez ensuite votre boîte mail.";
}
else {
document.getElementById("txt1").text="Enter your e-mail address and click on the button below";
document.getElementById("txt2").text="Then check your mail box";
}
}
</script>
<p id="txt1">Veuillez entrer votre adresse mail et cliquer sur le bouton ci-dessous.</p>
<p id="txt2">Consultez ensuite votre boîte mail.</p>
The event taken is from a select tag like so :
<select id="lan" name=lan onchange="select()" type=submit>
<option value="Français" selected>Français</option>
<option value="English">English</option>
</select>
The script above works perfectly when I'm changing text values for input tags, but for paragraph tags, it doesn't work... I probably forgot something... Thanks for helping !
Change it to:
<script>
function select()
{
if (document.getElementById("lan").value=="Français")
{
document.getElementById("txt1").innerHTML="Veuillez entrer votre adresse mail et cliquer sur le bouton ci-dessous.";
document.getElementById("txt2").innerHTML="Consultez ensuite votre boîte mail.";
}
else {
document.getElementById("txt1").innerHTML="Enter your e-mail address and click on the button below";
document.getElementById("txt2").innerHTML="Then check your mail box";
}
}
</script>

message via ajax is hiding fields

I have a problem I could not solve
I'm trying to send the message via ajax and update a div when sending the message
the only problem is that when I comment on something that updates a div field textarea and buttons just disappear
I also put a button to display the message field and buttons
Here is the code I'm using
<script type="text/javascript">
function hide_menu(){
if(document.getElementById('responder').style.display == "none"){
document.getElementById('responder').style.display = "block";
document.getElementById('button').style.display = "block"
$('html, body').animate({scrollTop:$('#responder').position().top});
}else{
document.getElementById('responder').style.display = "none"
document.getElementById('button').style.display = "none"
$('html, body').animate({scrollTop:$('#da-content-wrap').position().top});
}
}
</script>
<script type="text/javascript" language="javascript">
$(function($) {
// Quando o formulário for enviado, essa função é chamada
$("#da-ex-validate1").submit(function() {
// Colocamos os valores de cada campo em uma váriavel para facilitar a manipulação
var mensagem = $("#cleditor").val();
var user = $("#user").val();
// Fazemos a requisão ajax com o arquivo envia.php e enviamos os valores de cada campo através do método POST
$.post('<?= URL::getBase();?>form/insert/comment.php?id=<?=$_id;?>', {user: user, mensagem: mensagem }, function(resposta) {
// Quando terminada a requisição
// Exibe a div status
$("#status").slideDown();
// Se a resposta é um erro
if (resposta != false) {
// Exibe o erro na div
alert('Ocoreu um erro !');
}
// Se resposta for false, ou seja, não ocorreu nenhum erro
else {
$("#mensagens").load('<?= URL::getBase();?>load.php?id=<?= $_id;?>');
// Limpando todos os campos
$("#cleditor").val('');
}
});
});
});
</script>
Here is the HTML
<!-- Content Area -->
<div class="da-panel-content"> <img src="buildings.png" alt="" />Reply
<div id="mensagens">
<?= comments::_build($_id);?>
</div>
<form id="da-ex-validate1" class="da-form" method="post" action="javascript:func()" >
<div id="responder" style="display:none;">
<textarea id="cleditor" name="mensagem" class="large required"></textarea>
<input type="hidden" name="user" id="user" value="<? GetInfo::_id(NULL);?>"/>
</div>
<div class="da-button-row" id="button" style="display:none;">
<input type="reset" value="<?= $_LANG[137];?>" class="da-button gray left" />
<input type="submit" id="da-ex-growl-2" value="<?= $_LANG[219];?>" class="da-button red" />
</div>
</form>
</div>
where is "<?= comments::_build($_id);?>" is the list of records.
I also made ​​a page load.php practically calls the same function.
http://i.stack.imgur.com/V46Nr.jpg
sorry any mistake english :-)

Categories

Resources