Form submit with JavaScript - javascript

I'm having issues running my code can any one verifiy it and tell me why it's not working properly?. My javascript doesn't seems to be working fine and the best that I got was the first vars to display. I'm really new to javascript thought.
<!DOCTYPE html>
<html>
<head>
<title> Template Suivi Client </title>
<link rel="icon" href="icone.ico" type="image/x-icon">
<link rel="stylesheet" href="aidememoire.css">
<script>
function myFunction {
alert();
var compte = form.inputcompte.value;
var nom = form.inputnom.value;
var telephone = form.inputtelephone.value;
var quand = form.inputdate.value;
var hdebut = form.inputheuredebut.value;
var hfin = form.inputheurefin.value;
var info = form.inputdescription.value;
document.getElementById("displaycompte").innerHTML = ("Numéro de Compte Client: " + compte);
document.getElementById("displaynom").innerHTML = ("Nom du Client : " + nom);
document.getElementbyId("displaytelephone").innerHTML = ("Numéro de téléphone : ");
document.getElementbyId("displayquand").innerHTML =("Date :" + quand);
document.getElementbyId("displayheured").innerHTML = ("Heure de début : " + hdebut);
document.getElementById("displayheuref").innerHTML = ("Heure de fin: " +hfin);
document.getElementById("displaydescription").innerHTML =("Déscription :" + info);
}
</script>
</head>
<body>
<h2 style="text-align: Center">
Template Suivi Client
</h2>
<form method="get">
Numéro de Compte Client :
<input type="text" name="inputcompte">
<br><br>
Nom du Client :
<input type="text" name="inputnom">
<br><br>
Numéro de téléphone :
<input type="text" name="inputtelephone">
<br><br>
Date :
<input type="date" name="inputdate">
<br><br>
Heure de début :
<input type="time" name="inputheuredebut">
<br><br>
Heure de fin :
<input type="time" name="inputheurefin">
<br><br>
Description du problème :
<input type="text" name="inputdescription">
<br><br>
<button type="button" onclick="myFunction(from.here)"> Soummettre </button>
</form>
<br><br><br>
<p id="displayfinal"> Produit final s'affichera ici </p>
<p id="displaycompte">
</p>
<p id="displaynom">
</p>
<p id="displaytelephone">
</p>
<p id="displayquand">
</p>
<p id="displayheured">
</p>
<p id="displayheuref">
</p>
<p id="displaydescription">
</p>
</body>
</html>`

You are using a variable form that is not defined anywhere.
You can sent the reference to the form from the button:
onclick="myFunction(this.form)"
Catch the parameter in the function:
function myFunction(form) {

try giving the form an id, like <form id="abc" method="GET">...</form>
then use $("#abc").off('submit'); (after the end of the form)

The info that I got from the console [ Uncaught TypeError: Cannot read property 'inputcompte' of undefined ] . It happens to all my variables

Related

Passing a list of String from Spring Controller to Javascripts

I would like to pass a list of String from Spring Controller to Javascripts.
The Controller :
#PostMapping("/level1")
public String login (Model model){
List<Question> questions = frageRepository.findAllQuestions();
List<String> questionText = questions.stream().map(Frage::getText).toList();
model.addAttribute("questionText", questionText);
log.info(spieler.toString());
return "level1";
}
the body of level1.html
<body>
<div class="container mx-auto">
<label class="text-center mt-4" id="thetext">Du liebst Abenteuer und möchte endlich reisen.
<br>
Du hast ein bisschen Geld und das reicht für ein Ticket zur nächsten Insel.<br>
Unglücklicherweise ist dein Schiff in einem Sturm gesunken. <br>
Du hat glück, an einen Strand zu landen. <br><br>
Jetzt musst du die Herausforderungen mit deinen SQL-Kenntnissen meistern.<br>
Je schneller du die Probleme löst, desto besser ist dein Ranking.<br><br>
Viel Spaß !!!<br>
</label>
<div class="d-flex justify-content-center">
<input id="startButton" onclick="myFunction()" class="btn-secondary mt-4"
type="button" value="next">
</div>
</div>
<script>
var questionText = [[${questionText}]];
</script>
<script th:src="#{/script/questions.js}"></script>
</body>
the question.js file
var i = 0;
function myFunction() {
document.getElementById("thetext").innerHTML = questionText[i];
i++;
}
How can i pass the list questionText to Javascripts code? I want that when the user clicks the next button, the browser will show him the next question in label "thetext" from the list.
Or Is there another way to do this?
I hope, you can understand me :(
Thank you very much !
just input th:inline="javascript" in the script tag
<script input th:inline="javascript">
var questionText = [[${questionText}]];
</script>

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

post undefined index ajax/jquery upload to another php file

i found this code in jquery / ajax i edited a little but for some reason the output doesn't have a value.
here my code (javascript file):
function fototoevoegen(){
var fotonaam = document.getElementById('fotonaam').value
var text = document.getElementById('text').value
var file = new FormData();
console.log(fotonaam);
console.log(text);
console.log(file);
file.append('file',$('.file')[0].files[0]);
$.ajax({
url: "../assets/fototoevoegen.php",
type: "POST",
data:{ file, fotonaam, text},
processData: false,
contentType: false,
cache:false,
beforeSend:function(){
$(".result").text("Loading ...");
},
success:function(data){
$(".result").html(data);
alert(data);
}
});
return false;
}
the console.log does have value's but the output file (fototoevoegen say's undifend index to all vars :/
can someone help me on this ! thanks
//HTML file//
<!DOCTYPE html>
<html>
<head>
<title>CMS V1.2</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../css/style2.css">
</head>
<body>
<div class="content">
<h2>Foto Database</h2>
<br/>
<form method="post">
<input type="hidden" name="size" required="required" value="">
<div>
<input type="file" id="file" class="file">
</div>
<br/>
<div>
<input type="text" id="fotonaam" placeholder="fotonaam">
</div>
<br/>
<div>
<textarea id="text" cols="40" rows="4" placeholder="foto omschrijving"></textarea>
</div>
<br/>
<div>
<input type="button" value="Upload Foto" onclick="fototoevoegen();">
</div>
<br/>
</form>
</div>
<div class="container3Titel">
<h2>Alle foto's in het database </h2>
</div>
<div class="container3">
<?php foreach ($fotos as $foto){ ?>
<div class ="container3item">
<form method ="get">
<h2><?= $foto['foto_naam']?></h2>
<img src="<?= $foto['foto_url']?>" width="300" height="170"/>
<p> <?= $foto['foto_omschrijving']?> </p>
<p> <?= $foto['foto_url']?> </p>
<input type=hidden id="fotourl" value="<?= $foto['foto_url']?>">
<input type=hidden id="foto_id" value="<?= $foto['foto_id']?>">
<input type="button" name="verwijderen" value="Foto Verwijderen" onclick="fotoverwijderen();">
</form>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
Sent information to this file (../assets/fototoevoegen.php)
<?php
include_once('../includes/connection.php');
// de folder waar alle foto's worden opgeslagen
$folder = "../foto/";
$info = $_FILES["file"]["name"];
// extentie herkennen van het bestand en deze toevoegen aan de url
$ext = pathinfo($info, PATHINFO_EXTENSION);
$ext = '.'.$ext;
$naam = $_POST['fotonaam'].$ext;
$full_path = $folder.$naam;
// omschrijving en foto naam aan variable geven voor insert query
$omschrijving = $_POST['text'];
$fotonaam = $_POST['fotonaam'];
echo($naam);
echo($fotonaam);
echo($omschrijving);
echo($info);
// de foto of het bestand opslaan in een map (foto's)
if (move_uploaded_file($_FILES['foto']['tmp_name'], $full_path)) {
//als het uploaden gelukt is voer je een query uit naar de database zodat deze later nog gebruikt kan worden.
$query = $pdo->prepare("INSERT INTO fotobibliotheek (foto_naam,foto_omschrijving,foto_url) VALUES(?,?,?)");
$query->bindValue(1,$fotonaam);
$query->bindValue(2,$omschrijving);
$query->bindValue(3,$full_path);
$query->execute();
// succes melding weergeven en redirect naar pagina bibliotheek
echo "De foto is opgeslagen";
} else {
//fout melding als er niet geupload kan worden
echo 'uploaden mislukt';
}
?>
I think the problem is here:
data:{ file, fotonaam, text}
You need to append your values to your formData object and then send that object.
If you rearrange your code a little so that you handle the "submit" event of your form, instead of your button, then this becomes quite straightforward:
HTML:
<form id="fotoForm" method="post" enctype="multipart/form-data">
<input type="hidden" name="size" required="required" value="">
<div>
<input type="file" id="file" name="file" class="file">
</div>
<br/>
<div>
<input type="text" id="fotonaam" name="fotonaam" placeholder="fotonaam">
</div>
<br/>
<div>
<textarea id="text" cols="40" rows="4" name="text" placeholder="foto omschrijving"></textarea>
</div>
<br/>
<div>
<input type="submit" value="Upload Foto">
</div>
<br/>
</form>
JavaScript:
$(function() {
$("#fotoForm").submit(function(event) {
event.preventDefault(); //prevent default non-ajax postback
var data = new FormData(this); //pass the form into the formData object
$.ajax({
url: "../assets/fototoevoegen.php",
type: "POST",
data: data,
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
$(".result").text("Loading ...");
},
success: function(data) {
$(".result").html(data);
alert(data);
}
});
});
});
See also Uploading both data and files in one form using Ajax? for a similar example

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.

JS-validation doesn't work

I'm trying to validate the number of seats in a form I already wrote the JSP, provided the servlets. Now I'm trying to do the validation with JS, and I'm doing something wrong.
<script>
window.onload = function() {//zorgt ervoor dat eerst html-document wordt geladen vooraleer functies worden aangesproken
console.log("voor vrijePlaatsen");
function validate_form(e) {
console.log("in validate");
var plaatsen = document.getElementById("plaatsen");
var vrijePlaatsen = document.getElementById("beschikbaar");
console.log(plaatsen.value);
console.log(vrijePlaatsen.value);
if (plaatsen.value === "") {
alert("Gelieve een aantal plaatsen te reserveren");
plaatsen.focus();
e.preventDefault();
}
else if (plaatsen.value < 0) {
alert("Geef een positief aantal plaatsen in");
plaatsen.focus();
e.preventDefault();
}
else if (plaatsen.value > vrijePlaatsen.value) {
alert("U kan slechts " + vrijePlaatsen.value + " plaatsen reserveren./nU probeerde er " + vrijePlaatsen.value + " te reserveren");
plaatsen.focus();
e.preventDefault();
}
else if (isNaN(plaatsen.value)) {
alert("Gelieve een getal in te geven.")
plaatsen.focus();
e.preventDefault();
}
return true;
}
}
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="contextPath" value="${pageContext.servletContext.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cultuurhuis - Reservaties</title>
<link rel="stylesheet" href="${contextPath}/CSS/default.css"/>
</head>
<body>
<div id="container">
<div id="titel">
<h1>Het Cultuurhuis: Reserveren</h1>
</div>
<c:url value="/images/reserveren.png" var="imgReservering"/>
<img src="${imgReservering}"/>
<div id="content">
<c:url value="/voorstellingen" var="voorstellingen"/>
voorstellingen
<form method="post" action="${contextPath}/reservaties" >
<p id="voorstelling">Voorstelling:</p>
${voorstelling.titel}<br/>
<p>Uitvoerders: </p>
${voorstelling.uitvoerders}<br/>
<p>Datum: </p>
${voorstelling.datum}<br/>
<p>Prijs:</p>
${voorstelling.prijs}<br/>
<p>Vrije Plaatsen</p>
<p id ="beschikbaar">${voorstelling.vrijePlaatsen}</p><br/>
<br/>
<label>Plaatsen<br/>
<c:choose >
<c:when test="${not empty alGereserveerd}">
<c:set value="${alGereserveerd}" var="ingevuldePlaatsen"/>
</c:when>
<c:otherwise>
<c:set var="ingevuldePlaatsen" value="${param.plaatsen}"/>
</c:otherwise>
</c:choose>
<input id="plaatsen" type="text" name="plaatsen" value="${ingevuldePlaatsen}" autofocus/>
</label>
<input id="submitknop" type="submit" value="reserveren" onclick="return validate_form();" />
<p id="fout"></p>
<!--<span id="fout">${fouten}</span>-->
</form>
</div>
</div>
</body>
Change
<form method="post" action="${contextPath}/reservaties" >
To
<form method="post" action="${contextPath}/reservaties" onsubmit="return validate_form();">
Additionally move your validate_form function out of the onload scope, or use event listeners to attach it to the form within your onload
Also please explain your problem in the future so people don't have to figure it out for themselves :)
There are two problems.
You are trying to call validate_form when the submit button is clicked, but not if the form is submitted through some other means.
validate_form is not a global, so, when you try to call it, you get a reference error.
Bind your event handler to the form's submit when using Javascript while the function is in scope.
document.getElementsByTagName('form')[0].addEventListener('submit', validate_form);
function validate_form(e) {
console.log("in validate");
I'd add an ID to the form to make it easier to select with JavaScript.

Categories

Resources