Save data in .xls file with ajax, javascript and PHPExcel - javascript

I am practicing with ajax and javascript, and the following problem has arisen.
I need to send by POST the values of 2 text input and 1 drop-down list (select), and save that data in an excel file that I created on the server.
The .php file uses the classes provided by PHPExcel.
I click on the submit button, and it does not do anything.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Final</title>
<link rel="stylesheet" href="/css/styles.css" media="all">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<form action="/participantes/participantes.php" method="post" enctype="multipart/form-data">
<div class="main-data">
<p>
<label for="nombre">NOMBRE:</label>
<input type="text" name="nombre" id="nombre" placeholder="Escribí tu nombre" value="" required />
</p>
<p>
<label for="apellido">APELLIDO:</label>
<input type="text" name="apellido" id="apellido" placeholder="Escribí tu nombre" value="" required />
</p>
<p>
<label for="oficina">OFICINA:</label>
<select name="oficina" id="oficina" class="cajas" required>
<option value="">Seleccioná tu oficina</option>
<option value="1">SG</option>
<option value="2">SRIC</option>
<option value="3">SCAL</option>
</select>
</p>
<input type="submit" value="Guardar" id="save" name="save" onclick="save();"/>
</div>
</form>
<script src="/js/scripts.js"></script>
<script src="/js/md5.js"></script>
</body>
</html>
scripts.js
function save() {
// Recogemos los datos del formulario
var nombre = document.getElementById('nombre').value.toUpperCase();
var apellido = document.getElementById('apellido').value.toUpperCase();
var oficina = document.getElementById('oficina').value.toUpperCase();
// Definimos los parámetros que vamos a enviar
var parametros = "nombre="+nombre+"&apellido="+apellido+"&oficina="+oficina;
// Definimos la URL que vamos a solicitar via Ajax
var url = "http://localhost/participantes/participantes.php";
// Creamos un nuevo objeto encargado de la comunicación
var xhttp = new XMLHttpRequest();
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// console.log(this.response);
// }
// };
// Definimos como queremos realizar la comunicación
xhttp.open("POST", url, true);
// Ponemos las cabeceras de la solicitud como si fuera un formulario, necesario si se utiliza POST
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Enviamos la solicitud junto con los parámetros
xhttp.send(parametros);
console.log(url+parametros);
}
participantes.php
<?php
// Función para limpiar strings
function cleanFields($string) {
// Elimina espacios en blanco (u otro tipo de caracteres) del inicio y el final de la cadena
$string = trim($string);
// Retira las etiquetas HTML y PHP de una cadena
$string = strip_tags($string);
// Convierte caracteres especiales en entidades HTML
$string = htmlspecialchars($string);
// Si están activas las magic_quotes revierte su acción mediante stripslashes
if(get_magic_quotes_gpc()){
$string = stripslashes($string);
}
return($string);
}
if(isset($_POST["save"])) {
//Limpiar todos los campos recibidos
$fecha = date('d/m/Y');
$nombre = strtoupper(cleanFields($_POST["nombre"]));
$apellido = strtoupper(cleanFields($_POST["apellido"]));
$oficina = strtoupper(cleanFields($_POST["oficina"]));
$codigo = md5($nombre.$apellido);
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load("participantes.xlsx");
$objPHPExcel->setActiveSheetIndex(0);
$row = $objPHPExcel->getActiveSheet()->getHighestRow()+1;
//echo $row;
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$row, $fecha);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$row, $nombre);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$row, $apellido);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$row, $oficina);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$row, $codigo);
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('participantes.xlsx');
}
?>

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',
}

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

Dependent Select 2 levels

I need help :(
I've got a problem with dependent selects in two levels, I have two selects, one for country and other for city. The problem is that when I selected a country, the select cities shows me a part of my html page, I can't locate where I have the error ...
// JavaScript Document
var conexion = null;
function crearXMLHttpRequest() {
var xmlhttp=false;
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E){
if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
//declaramos los dropdowns del documento HTML
var listadoSelects = new Array();
listadoSelects[0] = "pais";
listadoSelects[1] = "ciudad";
/*funcion que devuelve la posicion donde esta el elemento dentro del array*/
function buscar(array, valor){
var i = 0;
while(array[i]){
if(array[i] == valor){
return i;
i++;
}
}
return null;
}
function cargarContenido(idOrigen){
//cojemos la posicion que ocupa el dropdown que tiene que ser puesto en el array
var posicionDestino = buscar(listadoSelects,idOrigen)+1;
//obtenemos el dropdown que el usuario ha modificado
var origen = document.getElementById(idOrigen);
//obtenemos la opcion seleccionada
var seleccionada = origen.options[origen.selectedIndex].value;
//si el usuario eligio la opcion Elige.. no buscaremos nada en la BBDD
if(seleccionada == ""){
var x = posicionDestino;
var actual = null;
//deshabilitamos las opciones de el select dependiente ya que no hemos seleccionado ningun valor
while(listadoSelects[x]){
actual = document.getElementById(listadoSelects[x]);
actual.length = 0;
var nuevaOpcion = document.createElement("option");
nuevaOpcion.value = 0;
nuevaOpcion.innerHTML = "Selecciona una opción..";
actual.appendChild(nuevaOpcion);
actual.disabled = true;
x++;
}
}else if(idOrigen != listadoSelects[listadoSelects.length-1]){
var idDestino = listadoSelects[posicionDestino];
var destino = document.getElementById(idDestino);
var ajax = crearXMLHttpRequest();
ajax.open("GET","action.php?action=dependientes&select="+idDestino+"&option="+seleccionada, true);
ajax.onreadystatechange = function(){
if(ajax.readyState == 1){
destino.length = 0;
var nuevaOp = document.createElement("option");
nuevaOp.value = 0;
nuevaOp.innerHTML = "Cargando...";
destino.appendChild(nuevaOp);
destino.disabled = true;
}if(ajax.readyState == 4){
destino.parentNode.innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="es-es">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="font-awesome-4.5.0/css/font-awesome.min.css"/>
<link href="css/css.css" rel="stylesheet" type="text/css" media="all" />
<link rel="stylesheet" type="text/css" href="css/icSquared_v1.0.css"/>
<title>Información del usuario</title>
</head>
<body>
<div>
<div class="registro">
<div class="container-fluid">
<div class="col-xs-12 col-sm-12 col-md-2" style="left:79%; margin-top:2%">
<?php echo $msgReg; ?>
<form action="action.php?accion=userRegisterInfo" method="post" role="form" enctype="multipart/form-data">
<h3 class="text-center" style="font-size:35px"> Datos Personales </h3><br />
<div class="form-group">
<label>Que eres?</label>
<?php desplegable_tipoUser(-1); ?>
</div>
<div class="form-group">
<label>Nombre</label>
<input type="text" name="nombre" class="form-control" required="required" placeholder="Introduce tu nombre"/>
</div>
<div class="form-group">
<label>Apellidos</label>
<input type="text" name="apellidos" class="form-control" required="required" placeholder="Introduce tus apellidos"/>
</div>
<div class="form-group">
<label>Fecha de nacimiento</label>
<input type="date" name="fechaNac" required="required" />
</div>
<div class="form-group">
<label>Sexo:</label><br />
<input type="radio" name="sexo" value="male" checked="checked"/> <i class="fa fa-mars fa-lg"></i> Hombre
<input type="radio" name="sexo" value="female" /> <i class="fa fa-venus fa-lg"></i> Mujer
</div>
<div class="form-group">
<label>Pais:</label>
<?php desplegable_pais(); ?>
</div>
<div class="form-group">
<label>Población:</label>
<select disabled="disabled" name="ciudad" id="ciudad">
<option value="0">Selecciona una opción..</option>
</select>
</div>
<div class="form-group">
<label>Imagen de Perfil:</label>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" enctype="multipart/form-data" name="foto_perfil" required="required">
</div>
<br/>
<input class="btn btn-success" type="submit" id="enviar" value="Guardar" style="margin-left:40%"/>
</form>
</div>
</div>
</div>
</div>
<script src="js/jquery-1.12.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/selectsDependientes.js"></script>
</body>
</html>
if you could help me would be a great help.
thanks to all! Here's the PHP code:
<?php
//connect BD function
function conectar(){
$connect = mysqli_connect("localhost","root","xxxx","xxxx");
//set the language
$connect->query("SET NAMES 'utf8'");
return $connect;
}
//disconect BD function
function desconectar($connect){
mysqli_close($connect);
}
//dropdown tipo usuario
function desplegable_tipoUser($idTUser){
$conexion = conectar();
$sql = "SELECT * FROM TUSUARIO";
echo '<select name="tusuario">';
if($resultado = $conexion -> query($sql)){
while($fila = mysqli_fetch_array($resultado)){
if($fila[0] == $idTuser){
echo '<option value="'.$fila[0].'" selected>'.$fila[1].'</option>';
}else{
echo '<option value="'.$fila[0].'">'.$fila[1].'</option>';
}
}
}
echo '</select>';
desconectar($conexion);
}
//dropdown pais
function desplegable_pais(){
$conexion = conectar();
$sql = "SELECT * FROM PAIS";
echo '<select name="pais" id="pais" onChange="get_ciudad(this.value);">';
echo '<option value="0">Elige un País</option>';
if($resultado=$conexion->query($sql)){
while($fila=mysqli_fetch_array($resultado)){
echo '<option value="'.$fila[0].'">'.$fila[1].'</option>';
}
}else{
echo '<p> Error en la conexion o consulta.. </p> <br />';
}
echo '</select>';
desconectar($conexion);
}
//dropdown de las poblaciones
function desplegable_ciudad(){
$conexion = conectar();
$sql = "SELECT * FROM POBLACION";
echo '<select name="ciudad" id="ciudad">';
echo '<option value="0">Elige una poblacion</option>';
if($resultado = $conexion -> query($sql)){
while($fila=mysqli_fetch_array($resultado)){
echo '<option value="'.$fila[0].'">'.$fila[2]." - ".$fila[3].'</option>';
}
}else{
echo '<p> Error en la conexion o consulta.. </p> <br />';
}
echo '</select>';
desconectar($conexion);
}
?>
<?php
if($action == "dependientes"){
$listadoSelects=array(
"pais"=>"lista_pais",
"ciudad"=>"lista_ciudad"
);
$destino = $_GET['select'];
$seleccionado = $_GET['option'];
//funcion que valida que el select enviado por GET exista
function validar($destino){
global $listadoSelects;
$validado = false;
if(!isset($listadoSelects[$destino])){
$validado = true;
}
return $validado;
}
//funcion que valida la opcion seleccionada
function validarOp($seleccionado){
$validado = false;
if(is_numeric($seleccionado)){
$validado = true;
}
return $validado;
}
if(validar($destino) && validarOp($seleccionado)){
$conexion = conectar();
$sql = "SELECT idPoblacion, nombre,comunidadAut FROM POBLACION WHERE id_pais='".$seleccionado."'";
if($resultado = $conexion -> query($sql)){
echo '<select name="'.$destino.'" id="'.$destino.'" onChange="cargarContenido(this.id)">';
echo '<option value="0">Elige</option>';
while($fila = mysqli_fetch_array($resultado)){
//$fila[0] = htmlentities($fila[0]);
echo "<option value='".$fila[0]."'>".$fila[1]." - ".$fila[2]."<option>";
}
}
}
?>

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