Dependent Select 2 levels - javascript

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>";
}
}
}
?>

Related

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

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');
}
?>

Confirmation message after inserted data in new page

Good day all, I'm new to PHP and I really need some help. I'm trying to make a confirmation message in new page after inserting data. I tried echo and print the results, But nothing work to me!!!!. This is the only problem I faced which I could not solved !!!
Code for request.php page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body dir="rtl">
<div class="container" style="width:400px;">
<div ng-app="myapp" ng-controller="formcontroller">
<form name="userForm" id="contact" ng-submit="insertData()">
<label class="text-success" ng-show="successInsert">{{successInsert}}</label>
<div class="form-group">
<label>name<span class="text-danger"></span>
</label>
<input type="text" name="name" ng-model="insert.name" class="form-control" /><span class="text-danger" ng-show="errorname">{{errorname}}</span>
</div>
<fieldset class="frmain">
<label>contact</label>
<div class="form-group">
<input type="text" name="em" ng-model="insert.em" class="form-control" placeholder="اemail" />
<span class="text-danger" ng-show="errorem">{{errorem}}</span>
<input type="text" name="telph" ng-model="insert.telph" class="form-control" placeholder="mobile" />
<span class="text-danger" ng-show="errortelph">{{errortelph}}</span>
</div>
<div class="form-group">
<label>department<span class="text-danger"></span>
</label>
<select ng-model="insert.dept" name="dept" class="form-control" style="font-family: times new roman;font-size: 18px;" />
<option value=""></option>
<option value="accounting department" </option>
<option value="huamn resources"></option>
<option value="IT department"></option>
</select>
<span class="text-danger" ng-show="errordept">{{errordept}}</span>
</div>
<div class="form-group" style="width: 320px;">
<label>details<span class="text-danger"></span>
</label>
<textarea name="det" ng-model="insert.det" class="form-control"></textarea>
<span class="text-danger" ng-show="errordet">{{errordet}}</span>
</div>
<div class="form-group">
<button name="submit" type="submit">send</button>
</div>
</form>
</div>
</div>
</body>
</html>
<script>
var application = angular.module("myapp", []);
application.controller("formcontroller", function($scope, $http) {
$scope.insert = {};
$scope.insertData = function() {
$http({
method: "POST",
url: "req_add.php",
data: $scope.insert,
}).success(function(data) {
if (data.error) {
$scope.errorname = data.error.name;
$scope.errorem = data.error.em;
$scope.errortelph = data.error.telph;
$scope.errordept = data.error.dept;
$scope.errordet = data.error.det;
$scope.successInsert = null;
} else {
$scope.insert = null;
$scope.errorname = null;
$scope.errorem = null;
$scope.errortelph = null;
$scope.errordept = null;
$scope.errordet = null;
$scope.successInsert = data.message;
}
});
}
});
</script>
Code for req_add.php page: (to insert data into DB)
<?php
//req_add.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$form_data = json_decode(file_get_contents("php://input"));
mysqli_query($connect,'set names utf8') or die (mysqli_error($connect));
$data = array();
$error = array();
$date1 = date('Y/m/d H:i:s');// 2017-07-12 10:35:45
$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
$no1 = $today . $rand;
if(empty($form_data->name))
{
$error["name"] = "name is required";
}
if(empty($form_data->em))
{
$error["em"] = "email is required";
}
if(empty($form_data->telph))
{
$error["telph"] = "mobile number is required";
}
if(empty($form_data->dept))
{
$error["dept"] = "department is required";
}
if(empty($form_data->det))
{
$error["det"] = "details are required";
}
if(!empty($error))
{
$data["error"] = $error;
}
else
{
$name = mysqli_real_escape_string($connect, $form_data->name);
$em = mysqli_real_escape_string($connect, $form_data->em);
$telph = mysqli_real_escape_string($connect, $form_data->telph);
$dept = mysqli_real_escape_string($connect, $form_data->dept);
$det = mysqli_real_escape_string($connect, $form_data->det);
$no = mysqli_real_escape_string($connect, $form_data->no1);
$reqdate = mysqli_real_escape_string($connect, $form_data->reqdate);
$answer = mysqli_real_escape_string($connect, $form_data->answer);
$query = "INSERT INTO requests(name, em, telph, dept, det, no, reqdate, answer) VALUES ('$name','$em', '$telph', '$dept', '$det', '$no1', '$date1', 'no answer')";
if(mysqli_query($connect, $query))
{
$data["message"] = "thank you for your request, your request nymber is: " .$no1;
}
}
echo json_encode($data);
?>
One useful option is to use mysqli_insert_id to get the last id inserted.
This function get the last id in the DB, not only in the inserted table, but is sufficient.
Another is in manual form, where the query return a custom value.
In your code :
$query ="INSERT INTO requests(name, em, telph, dept, det, no, reqdate,answer)
VALUES ('$name','$em', '$telph', '$dept', '$det', '$no1','$date1', 'no answer')";
if(mysqli_query($connect, $query))
{
$data["message"] = "thank you for your request, your request nymber is: " .$no1;
}
}
echo json_encode($data);
Add this changes :
$query = "INSERT INTO requests(name, em, telph, dept, det, no, reqdate, answer)
VALUES ('$name','$em', '$telph', '$dept', '$det', '$no1', '$date1', 'no answer')";
$query .="; select 1 as insert_ok;";
if($stmt=mysqli_query($connect, $query)) // Get result
{
$fetch = mysql_fetch_object($stmt);
if ($fetch->insert_ok) {
$data["message"] = "thank you for your request, your request nymber is: " .$no1;
}else{
$data["message"] = "The register wasn't inserted";
} // else
} //if $stmt
echo json_encode($data);
And in your script code: validate the insert_ok value returned from the php script.

Form Validation with JavaScript and PHP (Not refresh page on submit)

I am trying to do a form validation with JS that shows feedback as the user types. But of course when submitted the form it's sent using PHP. I already managed to do all of this the only problem I am having now is that when the form is submitted the page refreshes and my "Successfully sent" message cannot be seen. Here is my code and thanks a lot! :D
HTML FORM
<form method="post" id="emailForm" action="?">
<div class="form-group">
<label for="email">Email</label>
<input type="email" placeholder="ejemplo#gmail.com" class="form-control" name="email" id="email"/>
<p class="alert alert-danger errorEmail"></p>
</div>
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" placeholder="María Rodriguez" class="form-control" name="name" id="name"/>
<p class="alert alert-danger errorName"></p>
</div>
<div class="form-group">
<label for="asunto">Asunto</label>
<input type="text" placeholder="Garantía producto" class="form-control" name="asunto" id="asunto" /><span class="badge badgeA"></span>
<p class="alert alert-danger errorAsunto"></p>
</div>
<div class="form-group">
<label for="mensaje">Mensaje</label>
<textarea placeholder="Ingrese su mensaje aquí, trate de ser lo más claro y conciso posible." name="mensaje" id="mensaje" class="form-control" rows="7"></textarea><span class="badge badgeM"></span>
<p class="alert alert-danger errorMensaje"></p>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-success" value="Enviar!"/>
Field to display feedback of submission
<div class="alert alert-success enviado">
</div>
<div class="alert alert-danger noEnviado">
</div>
JavaScript (jQuery)
$(function() {
$(".errorEmail").hide();
$(".errorName").hide();
$(".errorAsunto").hide();
$(".errorMensaje").hide();
$(".enviado").hide();
$(".noEnviado").hide();
var error = false;
$('#email').keyup(function(){
checkEmail();
});
$('#name').keyup(function(){
checkName();
});
$('#asunto').keyup(function(){
checkAsunto();
});
$('#mensaje').keyup(function(){
checkMensaje();
});
function checkEmail() {
var email = $('#email').val();
error = false;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(email)) {
$('.errorEmail').hide();
}
else {
$('.errorEmail').html("Ingrese un correo electrónico válido.")
$('.errorEmail').show();
error = true;
}
}
function checkName() {
var name = $('#name').val().length;
var minName = 5;
var cantidad = - (name - minName);
error = false;
if (name < 5){
$('.errorName').html("Por favor ingrese su nombre. <b>Mínimo " + cantidad + " caracteres.</b>");
$('.errorName').show();
error = true;
}
else {
$('.errorName').hide();
}
}
function checkAsunto() {
var asunto = $('#asunto').val().length;
var minAsunto = 10;
var cantidad = - (asunto - minAsunto);
error = false;
if (asunto <10){
$('.errorAsunto').html("Por favor ingrese un asunto.<b> Mínimo " + cantidad + " caracteres.</b>");
$('.errorAsunto').show();
error = true;
}
else {
$('.errorAsunto').hide();
}
}
function checkMensaje() {
var email = $('#mensaje').val().length;
var minMensaje = 20;
var cantidad = - (email - minMensaje);
error = false;
if (email < 20){
$('.errorMensaje').html("Por favor ingrese un mensaje. <b> Mínimo " + cantidad + " caracteres. </b>");
$('.errorMensaje').show();
error = true;
}
else {
$('.errorMensaje').hide();
}
}
$('#emailForm').submit( function() {
checkEmail();
checkName();
checkAsunto();
checkMensaje();
if(error === false) {
$('.enviado').html("Mensaje enviado exitosamente");
$('.enviado').fadeIn(500);
$('.noEnviado').fadeOut(500);
return true;
} else {
$('.noEnviado').html("Ups... hubo un problema");
$('.noEnviado').fadeIn(500);
$('.enviado').fadeOut(500);
return false;
}
});
});
PHP
The PHP code is really simple some how it doesn't let me display it here but it just get's the $_POST values on the form and sends them using email();
Thanks guys
Instead of returning true replace it with an Ajax post request to the same script, on success show the message you wish.

Javascript Submit is not Sending SUBMIT POST to php file

I'm trying to create a form without a real submit button, but with a styled a href and javascript, but I'm unable to POST the form itself.
If I do var_dump($_POST); then I get an array of 4 items (3 inputs and 1 text area). The form itself is not there, so if (isset($_POST['submit'])) valuates to false. I also tried if (isset($_POST['ContactForm'])) but its not working either
form code:
<form name='ContactForm' id='ContactForm' action='verzendvraag.php' method='POST'>
<input type="text" class="col-md-6 col-xs-12 name" id="naam" name='naam' placeholder='Naam *' value="<? echo $_SESSION['naam']; ?>" required/>
<input type="email" class="col-md-6 col-xs-12 Email" id="email" name='email' placeholder='Email *' value="<? echo $_SESSION['email']; ?>" required/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' id='Subject' placeholder='Onderwerp'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" id="vraag" name="vraag" placeholder='Bericht *' style="left: 0px; top: 0px" required><? echo $_SESSION['vraag']; ?></textarea>
<div class="cBtn col-xs-12">
<ul>
<li class="clear"><i class="fa fa-times"></i>ledig vakjes</li>
<li class="send"><i class="fa fa-share"></i>Verstuur bericht</li>
</ul>
</div>
</form>
javascript:
function submitForm(e) {
if (validateForm())
{
document.getElementById("ContactForm").submit();
}
e.preventDefault();
}
php:
session_start();
//Validatie serverside => bescherming inbouwen voor als iemand zijn javascript uitschakelt. Javascript echter wel nodig om de server en netwerktraffic te ontlasten.
if (isset($_POST['submit']))
{
$naam = $_POST['naam'];
//$bedrijf = $_POST['bedrijf'];
$subject = $_POST['Subject'];
$email = $_POST['email'];
$vraag = $_POST['vraag'];
//In session steken zodat we bij een eventuele terugkeer naar de form de reeds ingevulde gegevens kunnen terug zetten.
$_SESSION['naam'] = $_POST['naam'];
//$_SESSION['bedrijf'] = $_POST['bedrijf'];
$_SESSION['Subject'] = $_POST['Subject'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['vraag'] = $_POST['vraag'];
$isOK = true;
$error = '0';
$atpos = strrpos($email,"#");
$dotpos = strrpos($email,".");
if(is_null($naam) || $naam == '')
{
$isOK = false;
echo('NAAM NIET OK ');
$error .= ',1';
}
if(is_null($email) || $email == '')
{
$isOK = false;
echo('EMAIL NIET OK '.$email);
$error .= ',2';
}
else
{
//checken geldig e-mailadres
if ($atpos === false || $dotpos === false || $dotpos < $atpos+2 || $dotpos+2 >= strlen($email)) //=== moet => http://php.net/manual/en/function.strpos.php en http://www.php.net/manual/en/language.operators.comparison.php
{
$isOK = false;
echo("Ongeldig e-mailadres ");
$error .= ',3';
}
}
if(is_null($vraag) || $vraag== '')
{
$isOK = false;
echo('VRAAG NIET OK ');
$error .= ',4';
}
}
if(!($isOK))
{
echo("<script>location.href='index.php?error=$error'</script>");
exit;
}
else
{
.....
}
I checked Javascript Submit is not Sending POST to php file and he says his code works, so I don't understand mine won't.
Since you don't have any button or input named submit so it does not exist in $_POST variable. I think you should check what you have in the form so use .
if (isset($_POST['naam'])){
// your code
}
Instead of
if (isset($_POST['submit'])){
// your code
}
you should also change this if (isset($_POST['submit'])) to if (isset($_POST['naam']))
Use ajax request like this
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "receive.php",
data: $("#ContactForm").serialize(),
success: function(response) {
if (response) {
alert('Successfully posted.');
}
else {
alert('Successfully not posted.');
}
}
});
Just use ajax for submiting form
<!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=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form name='ContactForm' id='ContactForm' action='verzendvraag.php' method='POST'>
<input type="text" class="col-md-6 col-xs-12 name" id="naam" name='naam' placeholder='Naam *' value="<? echo $_SESSION['naam']; ?>" required/>
<input type="email" class="col-md-6 col-xs-12 Email" id="email" name='email' placeholder='Email *' value="<? echo $_SESSION['email']; ?>" required/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' id='Subject' placeholder='Onderwerp'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" id="vraag" name="vraag" placeholder='Bericht *' style="left: 0px; top: 0px" required><? echo $_SESSION['vraag']; ?></textarea>
<div class="cBtn col-xs-12">
<ul>
<li class="clear"><i class="fa fa-times"></i>ledig vakjes</li>
<li class="send"><i class="fa fa-share"></i>Verstuur bericht</li>
</ul>
</div>
</form>
<script>
function submitForm(e) {
alert('working');
var naam = $("#naam").val();
var email = $("#email").val();
var Subject = $("#Subject").val();
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "verzendvraag.php",
data: {"naam":naam,"email":email,"Subject":Subject},
success: function(response) {
if (response) {
alert(response);
alert('Successfully posted.');
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
</body>
</html>
verzendvraag.php
<?php session_start();
//Validatie serverside => bescherming inbouwen voor als iemand zijn javascript uitschakelt. Javascript echter wel nodig om de server en netwerktraffic te ontlasten.
if (isset($_POST))
{
$naam = $_POST['naam'];
//$bedrijf = $_POST['bedrijf'];
$subject = $_POST['Subject'];
$email = $_POST['email'];
//$vraag = $_POST['vraag'];
//In session steken zodat we bij een eventuele terugkeer naar de form de reeds ingevulde gegevens kunnen terug zetten.
$_SESSION['naam'] = $_POST['naam'];
//$_SESSION['bedrijf'] = $_POST['bedrijf'];
$_SESSION['Subject'] = $_POST['Subject'];
$_SESSION['email'] = $_POST['email'];
//$_SESSION['vraag'] = $_POST['vraag'];
$isOK = true;
$error = '0';
$atpos = strrpos($email,"#");
$dotpos = strrpos($email,".");
if(is_null($naam) || $naam == '')
{
$isOK = false;
echo('NAAM NIET OK ');
$error .= ',1';
}
if(is_null($email) || $email == '')
{
$isOK = false;
echo('EMAIL NIET OK '.$email);
$error .= ',2';
}
else
{
//checken geldig e-mailadres
if ($atpos === false || $dotpos === false || $dotpos < $atpos+2 || $dotpos+2 >= strlen($email)) //=== moet => http://php.net/manual/en/function.strpos.php en http://www.php.net/manual/en/language.operators.comparison.php
{
$isOK = false;
echo("Ongeldig e-mailadres ");
$error .= ',3';
}
}
/* if(is_null($vraag) || $vraag== '')
{
$isOK = false;
echo('VRAAG NIET OK ');
$error .= ',4';
}*/
}
if(!($isOK))
{
echo("<script>location.href='index.php?error=$error'</script>");
exit;
}
else
{
echo "SUCCESS";
}
?>

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