Form Submission in Django without Page Refresh using AJAX - javascript

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.

Related

Property 'form' does not exist on type 'LoginComponent'

im having trouble to add a form to my website on angular, in the title its shows what its the error that VScode shows me.
Here is the LoginComponent.html
On line 1 under the word "form" its where vscode indicate my error, also on the words "form" on the bottom of the code.
<div>
<label for="email">Email: </label>
<input type="email" formControlName="email">
</div>
<div *ngIf="Mail?.errors && Mail?.touched">
<p *ngIf="Mail?.hasError('required')" class="error">
El email es requerido.
</p>
<p *ngIf="Mail?.hasError('email')" class="error">
El formato del email debe ser válido.
</p>
</div>
<br/>
<div>
<label for="exampleInputPassword1" class="form-label">Password: </label>
<input type="password" formControlName="password" [class.border-danger]="MailValid">
</div>
<div *ngIf="Password?.errors && Password?.touched">
<p *ngIf="Password?.hasError('required')" class="error">
El password es requerido.
</p>
<p *ngIf="Password?.errors?.minlength
" class="error">
El password debe ser de 8 o más caracteres.
</p>
</div>
<br/>
<div>
<button type="submit">Iniciar Sesión</button>
</div>
</form>
<div>
<p>Un debuger para mostrar que es posible hacer un biding directo al formulario <strong>{{form.value.email}} </strong><strong>{{form.value.password}} </strong><p> <--here also shows me the error.
<br>
</div>
And here is my LoginComponent.ts code, also shows me the error message "Property 'form' does not exist on type 'LoginComponent'" in every form word appareance.
import { Component, OnInit } from '#angular/core';
import {FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
// Inyectar en el constructor el formBuilder
constructor(private formBuilder: FormBuilder){
///Creamos el grupo de controles para el formulario de login
this.form= this.formBuilder.group({
password:['',[Validators.required, Validators.minLength(8)]],
email:['', [Validators.required, Validators.email]],
})
}
ngOnInit(): void {
}
get Password(){
return this.form.get("password");
}
get Mail(){
return this.form.get("email");
}
get PasswordValid(){
return this.Password?.touched && !this.Password?.valid;
}
get MailValid() {
return false
}
onEnviar(event: Event){
// Detenemos la propagación o ejecución del compotamiento submit de un form
event.preventDefault;
if (this.form.valid){
// Llamamos a nuestro servicio para enviar los datos al servidor
// También podríamos ejecutar alguna lógica extra
alert("Todo salio bien ¡Enviar formuario!")
}else{
// Corremos todas las validaciones para que se ejecuten los mensajes de error en el template
this.form.markAllAsTouched();
}
}
}
I can only assume one of the following is missing.
You haven't referenced the form in the HTML like <form [formGroup]="form">
You're missing the ReactiveFormsModule in your app.module.ts
But based on your code, I'm wondering... where did you even declare form? Don't you have any linter installed? No surprise that the template cannot find the form.

FETCH JavaScript PHP process the data on the server sent with fetch

I have this doubt of how to process the data brought from my form, I am using javascript with a fetch to receive the data of the form, but I have the doubt of how I should process them in php, nor is the click event of the send button working, the problem is that the server seems not to be receiving the array sent from javascript with the data, agradesco if you give me any source to delve into the topic of fetch api, I am new to javascript and php
my Javascript
registrar.addEventListener("click", () => {
fetch("../add.php", {
method: "post",
body: new FormData(frm) //frm es el id del formulario
}).then(response => response.text()).then
(response => {
// console.log(response);
// si la respuesta sel servidor es "ok" arroja una alerta personalizada
if (response == "ok") {
Swal.fire({
icon: 'success',
title: 'Registrado',
showConfirmButton: false,
timer: 1500
})
frm.reset();
}
}
)
})
<form action="" method="post" id="frm">
<div class="form-group">
<br>
<div class="form-group">
<div class="form-group">
<input type="text" name="name_usu" id="name_usu" class="form-control form-control-md" placeholder="Nombre completo" required >
</div>
<input type="text" name="phone_usu" id="phone_usu" class="form-control form-control-md" placeholder="Numero de teléfono" required>
</div>
<input type="email" name="nom_usu" id="nom_usu" class="form-control form-control-md" placeholder="Email" required></div>
<input type="text" name='torreApto' id="Torre_apto" class="form-control form-control-md" placeholder="Torre y apartamento" required>
<label for="FormControlSelect1" class="text-light">Escoja tipo de residente</label>
<select class="form-control" name="sel_apto" id="sel_apto" required>
<option selected>Propietario</option>
<option selected>Arrendado</option>
<option selected>Otro</option>
</select>
<div class="form-group">
<label for="Textarea1" class="text-light">Mensaje a enviar</label>
<textarea class="form-control" name="mensaje" id="Textarea1" rows="3"></textarea>
</div>
<br>
<input type="button" class="btn btn-outline-light btn-block border-light text-light font-weight-bold" value="registrar" id="registrar">
</form>
addRegister.php
enter if (isset($_POST)) {
$nombre = $_POST['name_usu'];
$telefono = $_POST['phone_usu'];
$email = $_POST['nom_usu'];
$torreApto = $_POST['torreApto'];
$arrendado = $_POST['sel_apto'];
$mensaje = $_POST['mensaje'];
require("connect.php");
// script guardando en la base de datos
$query = $con->prepare("INSERT INTO informacion(nombre,telefono,email,torreApto,arrendado,mensaje) VALUES (:nom, :tel, :ema, :torr, :arr, :men)");
$query->bindParam(":nom", $nombre);
$query->bindParam(":tel", $telefono);
$query->bindParam(":ema", $email);
$query->bindParam(":torr", $torreApto);
$query->bindParam(":arr", $arrendado);
$query->bindParam(":men", $mensaje);
//ejecuta el script
$query->execute();
$con = null;
echo "ok";
}
Try to add
$_POST = file_get_contents('php://input');
at the beginning of your file.
You are not initializing the FormData correctly. To fill it with the data of a form you have to pass in a reference to the form. Currently you are passing in an undefined variable, that just happens to be the same as the ID of the form.
You need to get a reference to the form using, for example, getElementById:
new FormData(document.getElementById("frm"))

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

Form submit with 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

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