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

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

Related

Fetch call to PHP from remote client no error and no data

I've a problem with calling from Fetch javascript API from a local client to a remote server with PHP.
There are no errors but any data is returned.
When I make same call to the same server where the client is, it works.
same server:
Client: http://localhost:8888/myclient.html
Server: http://localhost:8888/myphp.php //Mamp
It works and returns the JSON.
Remote:
Client: http://127.0.0.1:5000
Server: http://localhost:8888/myphp.php
No errors!! But returns simply nothing
Client code:
<form target="_self" name="formulario" id="formulario">
<!-- Estamos usando lista desordenada para los campos de formulario
Es también habitual hacerlo con los elementos de los menús de navegación
-->
<ul>
<!--
H1 y H2 aquí van dentro de la etqueta UL para que no se solape con los campos,
ya que este UL está en posición absoluta
-->
<h2>Envíanos tus datos</h2>
<h1>Cubre el formulario</h1>
<!--
Empiezan los campos de formulario
-->
<li>
<!-- Campo obligatorio tipo texto-->
<label for="nombre"><span class="required">*</span> Tu nombre</label><br>
<input type="text" name="nombre" id="nombre" required>
</li>
<li>
<!-- Campo tipo numérico-->
<label for="edad">Tu edad</label><br>
<input type="number" name="edad">
</li>
<li>
<!-- Campo obligatorio tipo Email-->
<label for="email"><span class="required">*</span> Email</label><br>
<input type="email" name="email" id="email" required>
</li>
<li>
<!-- Campo tipo Tel (teléfono)-->
Teléfono <br>(formato xxx yyy zzz):<br>
<input type="tel" name="tel">
</li>
<li>
<!-- inputs tipo Radio-button Llevan el mismo nombre
para que se reciba un solo dato. Es un solo campo con dos inputs que
se marca además como obligatorio
-->
<span class="required">*</span> ¿Cómo vendrás al centro?
<hr>
<input type="radio" id="vehiculo" name="comoviene" value="vehiculo" required>
<label for="vehiculo">Tengo vehículo</label><br>
<input type="radio" id="andando" name="comoviene" value="andando">
<label for="andando">Voy andando</label>
</li>
<li>
<!-- inputs tipo checkbox. Cada uno es un campo.
-->
¿ Qué vehículos tienes ?<br>
<input type="checkbox" id="coche" name="tipo" value="coche">
<label for="coche">Tengo coche</label><br>
<input type="checkbox" id="moto" name="moto" value="moto">
<label for="moto">Tengo moto </label><br>
<input type="checkbox" id="barco" name="barco" value="barco">
<label for="barco">Tengo barco</label>
</li>
<li>
<!-- Campo tipo select, que crea un menú desplegable con las ociones
-->
¿Qué curso quieres?
<label for="curso">Elige uno</label>
<select name="curso" id="curso">
<option value="">Elige uno...</option>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<!-- Este sería el valor seleccionado por defecto
-->
<option value="JS" selected>JAVASCRIPT</option>
</select>
</li>
<li>
<!-- Botón de enviar.
Es un input pero no envía valores,
aunque tiene un value que es el texto que se ve en el botón,
y por defecto (si no se pone) es "submit".
-->
<input type="submit" name="Enviar" value="Enviar">
</li>
</ul>
</form>
<script>
let formul = document.getElementById('formulario');
let path = "http://localhost:8888/CLASE/CURSO-IFCD0110/hola-background/";
formul.onsubmit = function (e) {
e.preventDefault();
async function envio() {
const datos = new FormData(e.target);
let toSend = Object.fromEntries(datos);
// console.log(toSend)
let enviar = await fetch(path + 'form.php',
{
method: 'POST',
/*
* We also need to stringify the values, turn the
* JavaScript object to a single string that is accepted
* as JSON. So we are sending one string that contains
* all our values
*/
mode: 'no-cors',
body: JSON.stringify(toSend),
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
}
});
let escribir = await enviar.json();
document.body.innerHTML = JSON.stringify(escribir)
}
envio();
}
</script>
Server code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, FETCH, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-
Control-Allow-Headers, Authorization, X-Requested-With");
$data = json_decode(file_get_contents('php://input'), true);
echo json_encode($data);
exit;
Thanks!
EDIT.
Screenshots network tabs
The problem is the set of "no-coors". Without that, works correctly both local and remote.
The problem was I'd tested without the correct headers in the php file.
So the settings are:
{
method: 'POST',
/*
* We also need to stringify the values, turn the
* JavaScript object to a single string that is accepted
* as JSON. So we are sending one string that contains
* all our values
*/
// mode: 'no-cors', No-cors was the problem. Thanks for the comments.
body: JSON.stringify(toSend),
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
}

Form Submission in Django without Page Refresh using AJAX

I'm a newbie in python so this might be fixed easily.
I'm trying to do a register form using Jquery with Django.
I've been following this tutorial
when I click on the button it shows me the success message in the alert but nothing is inserted in the database.
Here is my code :
register.html
<body>
<form id="add_user_form">
{% csrf_token %}
{# label et input du uti_login de la class Form#}
<label for="UTI_LOGIN">Insérer un surnom d'utilisateur</label>
<input id="UTI_LOGIN" type="text" name="UTI_LOGIN">
<br>
{# label et input du UTI_NOM de la class LoginForm#}
<label for="UTI_NOM">Insérer un nom d'utilisateur</label>
<input id="UTI_NOM" type="text" name="UTI_NOM">
<br>
{# label et input du UTI_PRENOM de la class LoginForm#}
<label for="UTI_PRENOM">Insérer un prenom d'utilisateur</label>
<input id="UTI_PRENOM" type="text" name="UTI_PRENOM">
<br>
{# label et input du UTI_CIVILITE de la class LoginForm#}
<label for="UTI_CIVILITE">Insérer un civilite d'utilisateur</label>
<input id="UTI_CIVILITE" type="text" name="UTI_CIVILITE">
<br>
{# label et input du UTI_EMAIL de la class LoginForm#}
<label for="UTI_EMAIL">Insérer un email d'utilisateur</label>
<input id="UTI_EMAIL" type="text" name="UTI_EMAIL">
<br>
{# label et input du uti_mdp de la class LoginForm#}
<label for="UTI_MDP">Insérer mot de passe</label>
<input id="UTI_MDP" type="password" name="UTI_MDP">
<br>
<label for="UTI_SUPPRIME">Hidden label checked</label>
<input id="UTI_SUPPRIME" type="checkbox" hidden checked>
<br>
<br>
<input value="S'inscrire ! ☺" type="submit">
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).on('submit','#add_user_form',function (e) {
{# prevent the page getting refreshed#}
e.preventDefault();
$.ajax({
type:'POST',
url: 'registerSearch',
data:{
username:$('#UTI_LOGIN').val(),
mdp:$('#UTI_MDP').val(),
nom:$('#UTI_NOM').val(),
prenom:$('#UTI_PRENOM').val(),
civilite:$('#UTI_CIVILITE').val(),
email:$('#UTI_EMAIL').val(),
supp:$('#UTI_SUPPRIME').val(),
csrfmiddlewaretoken: $('input[name = csrfmiddlewaretoken]').val()
},
success:function () {
alert("Utilisateur crée !");
}
})
});
</script>
</html>
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'register', views.register_list, name='register'),
url(r'registerSearch', views.registersearch_list),
]
views.py
def register_list(request):
return render(request, 'esigapp/register.html', {})
def registersearch_list(request):
if request.method == 'POST':
username = request.POST['username']
mdp = request.POST['mdp']
nom = request.POST['nom']
prenom = request.POST['prenom']
civil = request.POST['civilite']
email = request.POST['email']
supp = request.POST['supp']
Sie_utilisateur.objects.create(
UTI_LOGIN=username,
UTI_MDP=mdp,
UTI_NOM=nom,
UTI_PRENOM=prenom,
UTI_CIVILITE=civil,
UTI_EMAIL=email,
UTI_SUPPRIME=supp
)
return HttpResponse('')
and finally
models.py
class Sie_utilisateur(models.Model):
UTI_LOGIN = models.CharField(max_length=50)
UTI_MDP = models.CharField(max_length=50)
UTI_NOM = models.CharField(max_length=50)
UTI_PRENOM = models.CharField(max_length=50)
UTI_CIVILITE = models.CharField(max_length=1)
UTI_EMAIL = models.CharField(max_length=50)
UTI_SUPPRIME = models.BooleanField()
def __str__(self):
return self.UTI_NOM
Some tips are also useful :)
Thanks
The problem is not Ajax. It's simply that you didn't anchor or terminate your URL patterns; so the URL "/registerSearch" matches the first one, "register".
Make sure you use beginning and end anchors:
url(r'^register$', views.register_list, name='register'),
url(r'^registerSearch$', views.registersearch_list),
You should probably also return something explicit in your registerSearch view so that your Ajax knows that the item has actually been created.

Triggering bootstrap modal on form submit and not on click

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

How to add user input into a existing SPARQL query

I want to integrate the user's input into a SPARQL query. Here's my existing code but I cannot get it to work.
javascript in external JS file:
$('#submit99').on('click', function(e) {
var userInput = $('#messageInput').val();
var query = "PREFIX own: <http://www.owl-ontologies.com/travel.owl#>" +
"PREFIX trvl: <http://www.owl-ontologies.com/travel.owl#>" +
"select distinct ?label where {" +
"?s a trvl:" + userInput + " ."
"OPTIONAL {" +
"?type rdfs:label ?label }" +
"}";
var endpoint = 'http://localhost:5820/finalProject/query';
var format = 'JSON';
$.get('/sparql',data={'endpoint': endpoint, 'query': query, 'format': format}, function(json){
var pre = $('<pre></pre>');
pre.text(JSON.stringify(json));
$('#linktarget99').html(pre);
});
});
my form:
<div class="header">
<div class="container">
<h1> Zoek de plek voor je favoriete activiteiten </h1>
<p class="beschrijving"> Wil je weten op welke plek jij bepaalde activiteiten kunt doen? Vul hieronder de activiteit in en wij zoek het voor je uit! tutorial </p>
<form role='form'>
<div class='form-group'>
<textarea class='form-control' id='messageInput' placeholder='type some nifty schilderij' row='1'> </textarea>
</div>
</form>
<div><a id="submit99" class='btn btn-primary'>Zoek de locatie van het schilderij</a></div>
</div>
</div>
This is the error I get from the terminal:
127.0.0.1 - - [14/Oct/2015 20:02:52] "GET /sparql?endpoint=http%3A%2F%2Flocalhost%3A5820%2FfinalProject%2Fquery&query=PREFIX+own%3A+%3Chttp%3A%2F%2Fwww.owl-ontologies.com%2Ftravel.owl%23%3EPREFIX+trvl%3A+%3Chttp%3A%2F%2Fwww.owl-ontologies.com%2Ftravel.owl%23%3Eselect+distinct+%3Flabel+where+%7B%3Fs+a+trvl%3A++BedAndBreakfast.&format=JSON HTTP/1.1" 200 -
It's fixed. The value given by the userinput container spaces which (...) up the code.

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>

Categories

Resources