Editar al clicar funcional

This commit is contained in:
Markines16 2021-06-06 01:01:34 +02:00 committed by GitHub
parent db5c5d79ad
commit bef1bb8038
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 411 additions and 161 deletions

View File

@ -56,6 +56,7 @@ class Evento implements \JsonSerializable
while($fila = $rs->fetch_assoc()) { while($fila = $rs->fetch_assoc()) {
$result = new Evento(); $result = new Evento();
$result->asignaDesdeDiccionario($fila); $result->asignaDesdeDiccionario($fila);
} }
$rs->free(); $rs->free();
} else { } else {
@ -282,7 +283,7 @@ class Evento implements \JsonSerializable
/** /**
* @param array[string] Nombre de las propiedades de la clase. * @param array[string] Nombre de las propiedades de la clase.
*/ */
const PROPERTIES = ['id', 'userId', 'title', 'start', 'end', 'idfilm']; const PROPERTIES = ['id', 'userId', 'title', 'start', 'end', 'idfilm', 'start_time', 'seat_price', 'format', 'seats_full'];
//'idfilm','idhall','idcinema','date', 'start_time', 'seat_price', 'format', 'seats_full']; //'idfilm','idhall','idcinema','date', 'start_time', 'seat_price', 'format', 'seats_full'];
private $id; private $id;
@ -292,16 +293,10 @@ class Evento implements \JsonSerializable
private $end; private $end;
private $idfilm; private $idfilm;
/*
private $idhall;
private $idcinema;
private $date;
private $start_time; private $start_time;
private $seat_price; private $seat_price;
private $format; private $format;
private $seats_full;*/ private $seats_full;
private function __construct() private function __construct()
@ -313,6 +308,11 @@ class Evento implements \JsonSerializable
return $this->id; return $this->id;
} }
public function getIdfilm()
{
return $this->idfilm;
}
public function getUserId() public function getUserId()
{ {
return $this->userId; return $this->userId;
@ -391,13 +391,19 @@ class Evento implements \JsonSerializable
* @return Devuelve un objeto con propiedades públicas y que represente el estado de este evento. * @return Devuelve un objeto con propiedades públicas y que represente el estado de este evento.
*/ */
public function jsonSerialize() public function jsonSerialize()
{ {
$o = new \stdClass(); $o = new \stdClass();
$o->id = $this->id; $o->id = $this->id;
$o->userId = $this->userId; $o->userId = $this->userId;
$o->title = $this->title; $o->title = $this->title;
$o->start = $this->start->format(self::MYSQL_DATE_TIME_FORMAT); $o->start = $this->start->format(self::MYSQL_DATE_TIME_FORMAT);
$o->end = $this->end->format(self::MYSQL_DATE_TIME_FORMAT); $o->end = $this->end->format(self::MYSQL_DATE_TIME_FORMAT);
$o->start_time = $this->start_time;
$o->seat_price = $this->seat_price;
$o->format = $this->format;
$o->film = Session::getThisSessionFilm($this->idfilm);
return $o; return $o;
} }
@ -419,13 +425,10 @@ class Evento implements \JsonSerializable
"start" => $start, "start" => $start,
"end" => $end, "end" => $end,
"idfilm" => $session->getIdfilm(), "idfilm" => $session->getIdfilm(),
/*"idcinema" => $session->getIdcinema(),
"idhall" => $session->getIdhall(),
"date" => $session->getDate(),
"start_time" => $session->getStartTime(), "start_time" => $session->getStartTime(),
"seat_price" => $session->getSeatPrice(), "seat_price" => $session->getSeatPrice(),
"format" => $session->getFormat(), "format" => $session->getFormat(),
"seats_full" => $session->getSeatsFull(),*/ "seats_full" => $session->getSeatsFull(),
); );
return $dictionary; return $dictionary;
@ -545,34 +548,6 @@ class Evento implements \JsonSerializable
} }
} }
/*
if (array_key_exists('idhall', $diccionario)) {
$idhall = $diccionario['idhall'] ?? null;
if (empty($idhall)) {
// throw new \BadMethodCallException('$diccionario[\'end\'] no puede ser una cadena vacía o nulo');
} else {
$this->idhall = $idhall;
}
}
if (array_key_exists('idcinema', $diccionario)) {
$idcinema = $diccionario['idcinema'] ?? null;
if (empty($idcinema)) {
// throw new \BadMethodCallException('$diccionario[\'end\'] no puede ser una cadena vacía o nulo');
} else {
$this->idcinema = $idcinema;
}
}
if (array_key_exists('date', $diccionario)) {
$date = $diccionario['date'] ?? null;
if (empty($date)) {
// throw new \BadMethodCallException('$diccionario[\'end\'] no puede ser una cadena vacía o nulo');
} else {
$this->date = $date;
}
}
if (array_key_exists('start_time', $diccionario)) { if (array_key_exists('start_time', $diccionario)) {
$start_time = $diccionario['start_time'] ?? null; $start_time = $diccionario['start_time'] ?? null;
if (empty($start_time)) { if (empty($start_time)) {
@ -607,7 +582,7 @@ class Evento implements \JsonSerializable
} else { } else {
$this->seats_full = $seats_full; $this->seats_full = $seats_full;
} }
}*/ }
self::compruebaConsistenciaFechas($this->start, $this->end); self::compruebaConsistenciaFechas($this->start, $this->end);

View File

@ -59,18 +59,17 @@ switch($_SERVER['REQUEST_METHOD']) {
} }
// Generamos un array de eventos en formato JSON // Generamos un array de eventos en formato JSON
$json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK); $json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
http_response_code(200); // 200 OK http_response_code(200); // 200 OK
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
header('Content-Length: ' . mb_strlen($json)); header('Content-Length: ' . mb_strlen($json));;
echo $json; echo $json;
break; break;
// Añadir un nuevo evento // Añadir un nuevo evento
case 'POST': case 'POST':
$errors = []; $errors = [];
$data = []; $data = [];
//Testing hacks
$correct_response = 'Operación completada'; $correct_response = 'Operación completada';
$entityBody = file_get_contents('php://input'); $entityBody = file_get_contents('php://input');
@ -103,14 +102,12 @@ switch($_SERVER['REQUEST_METHOD']) {
$start = date('Y-m-d', $start); $start = date('Y-m-d', $start);
$end = date('Y-m-d', $end); $end = date('Y-m-d', $end);
if($start >= $end) if($start > $end)
$errors['date'] = 'La fecha inicial no puede ser antes o el mismo dia que la final.'; $errors['date'] = 'La fecha inicial no puede ser antes o el mismo dia que la final.';
} }
if (empty($startHour)) if (empty($startHour))
$errors['startHour'] = 'Es necesario escoger el horario de la sesion.'; $errors['startHour'] = 'Es necesario escoger el horario de la sesion.';
error_log("El valor de idfilm: ".$idfilm);
if (!is_numeric($idfilm) && $idfilm <= 0 ) if (!is_numeric($idfilm) && $idfilm <= 0 )
$errors['idfilm'] = 'No se ha seleccionado una pelicula.'; $errors['idfilm'] = 'No se ha seleccionado una pelicula.';
@ -118,7 +115,7 @@ switch($_SERVER['REQUEST_METHOD']) {
$msg = Session::create_session($_SESSION["cinema"], $hall, $startHour, $startDate, $idfilm, $price, $format); $msg = Session::create_session($_SESSION["cinema"], $hall, $startHour, $startDate, $idfilm, $price, $format);
if(strcmp($msg,$correct_response)!== 0) if(strcmp($msg,$correct_response)!== 0)
$errors['price'] = $msg; $errors['global'] = $msg;
else else
$data['message'] = $msg; $data['message'] = $msg;
@ -136,7 +133,7 @@ switch($_SERVER['REQUEST_METHOD']) {
break; break;
case 'PUT': case 'PUT':
error_log("PUT"); /*
// 1. Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX // 1. Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX
$idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT); $idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT);
// 2. Leemos el contenido que nos envían // 2. Leemos el contenido que nos envían
@ -162,8 +159,83 @@ switch($_SERVER['REQUEST_METHOD']) {
header('Content-Length: ' . mb_strlen($json)); header('Content-Length: ' . mb_strlen($json));
echo $json; echo $json;
*/
//If the user want to move a session
if(isset($_GET["resize"]) && $_GET["resize"]){
}else{
$errors = [];
$data = [];
$correct_response = 'Se ha editado la session con exito';
$entityBody = file_get_contents('php://input');
$dictionary = json_decode($entityBody);
if (!is_object($dictionary))
$errors['global'] = 'El cuerpo de la petición no es valido';
$price = $dictionary->{"price"} ?? "";
$format = $dictionary->{"format"} ?? "";
$hall = $dictionary->{"hall"} ?? "";
$startDate = $dictionary->{"startDate"} ?? "";
$endDate = $dictionary->{"endDate"} ?? "";
$startHour = $dictionary->{"startHour"} ?? "";
$idfilm = $dictionary->{"idFilm"} ?? "";
$or_hall = $dictionary->{"og_hall"} ?? "";
$or_date = $dictionary->{"og_date"} ?? "";
$or_start = $dictionary->{"og_start"} ?? "";
if (empty($price) || $price <= 0 )
$errors['price'] = 'El precio no puede ser 0.';
if (empty($format))
$errors['format'] = 'El formato no puede estar vacio. Ej: 3D, 2D, voz original';
if (empty($hall) || $hall<=0 )
$errors['hall'] = 'La sala no puede ser 0 o menor';
if (empty($startDate))
$errors['startDate'] = 'Las sesiones tienen que empezar algun dia.';
else if (empty($endDate))
$errors['endDate'] = 'Las sesiones tienen que teminar algun dia.';
else {
$start = strtotime($startDate);
$end = strtotime($endDate);
$start = date('Y-m-d', $start);
$end = date('Y-m-d', $end);
if($start > $end)
$errors['date'] = 'La fecha inicial no puede ser antes o el mismo dia que la final.';
}
if (empty($startHour))
$errors['startHour'] = 'Es necesario escoger el horario de la sesion.';
if (!is_numeric($idfilm) && $idfilm <= 0 )
$errors['idfilm'] = 'No se ha seleccionado una pelicula.';
if(empty($errors)){
$msg = Session::edit_session($_SESSION["cinema"], $or_hall, $or_date, $or_start, $hall, $startHour, $startDate, $idfilm, $price, $format);
if(strcmp($msg,$correct_response)!== 0)
$errors['global'] = $msg;
else
$data['message'] = $msg;
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
}
}
echo json_encode($data);
break; break;
case 'DELETE': case 'DELETE':
// 1. Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX // 1. Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX
$idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT); $idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT);
// 2. Borramos el evento // 2. Borramos el evento

View File

@ -0,0 +1,99 @@
<?php
require_once($prefix.'assets/php/includes/film_dao.php');
class EditSessionForm {
public static function getForm(){
$films = new Film_DAO("complucine");
$filmslist = $films->allFilmData();
$form='
<div id="operation_msg" class="operation_msg"> </div>
<form id="new_session_form" name="new_session_form" action="eventos.php.php" method="POST">
<div id="global_group" class="form_group"></div>
<fieldset>
<legend>Datos</legend>
<div id="price_group" class="form_group">
<input type="number" step="0.01" id="price" name="price" value="" min="0" placeholder="Precio de la entrada" /> <br>
</div>
<div id="format_group" class="form_group">
<input type="text" id="format" name="format" value="" placeholder="Formato de pelicula" /> <br>
</div>
<div id="hall_group" class="form_group">
<select id="hall" name="hall" class="button large">>';
foreach(Hall::getListHalls($_SESSION["cinema"]) as $hll){
$form.= '
<option value="'. $hll->getNumber() .'"> Sala '. $hll->getNumber() .'</option>';
}
$form.=' </select>
</div>
</fieldset>
<fieldset>
<legend>Horario</legend>
<div id="date_group" class="form_group">
<div class="two-inputs-line">
<label> Fecha inicio </label>
<label> Fecha final </label>
<input type="date" id="startDate" name="startDate" value=""/>
<input type="date" id="endDate" name="endDate" value=""/>
</div>
</div>
<div id="hour_group" class="form_group">
<div class="one-input-line">
<label> Hora sesion </label>
<input type="time" id="startHour" name="startHour" value=""/>
</div>
</div>
</fieldset>
<input type="reset" id="reset" value="Limpiar Campos" >
<input type="submit" id="submit_new" name="sumbit" class="primary" value="Añadir" />
<div class="two-inputs-line" id="edit_inputs">
<input type="submit" id="submit_edit" name="sumbit" class="primary" value="Editar" />
<input type="submit" id="submit_del" name="sumbit" class="primary" inclick="confirm("¿Seguro que quieres eliminar esta sesion?")value="Borrar" />
</div>
<div id="film_msg_group" class="form_group"> </div>
<div id="film_group" class="form_group">
<div class="code showtimes">
<input type="hidden" id="film_id" name="film_id" value=""/>
<h2 id="film_title"> titulo </h2>
<hr />
<div class="img_desc">
<div class="image"> <img src="../img/films/iron_man.jpg" alt="iron man" id="film_img" /> </div>
<div class="blockquote">
<p id="film_desc">"Un empresario millonario construye un traje blindado y lo usa para combatir el crimen y el terrorismo."</p>
</div>
</div>
<li id="film_dur"> Duración: duracion minutos</li>
<li id="film_lan"> Lenguaje: idioma </li>
</div>
<button type="button" class="button large" id="return"> Cambiar pelicula </button>
</div>
<div class="film_list" id="film_list">
<ul class="tablelist col3">';
$parity = "odd";
$i = 0;
foreach($filmslist as $film){
$form .='<div class="'.$parity.'">
<input type="hidden" value="'.$film->getId().'" id="id'.$i.'"/>
<input type="hidden" value="'.$film->getImg().'" id="img'.$i.'"/>
<input type="hidden" value="'.$film->getLanguage().'" id="lan'.$i.'"/>
<input type="hidden" value="'.$film->getDescription().'" id="desc'.$i.'"/>
<li value="'.$film->getTittle().'"id="title'.$i.'"> '. str_replace('_', ' ',$film->getTittle()).'</li>
<li id="dur'.$i.'"> '.$film->getDuration().' min</li>
<li> <button type="button" class="film_button" id="'.$i.'"> Seleccionar </button> </li>
</div>
';
$parity = ($parity == "odd") ? "even" : "odd";
$i++;
}
$form.='
</ul>
</div>
</form>';
return $form;
}
}
?>

View File

@ -10,7 +10,13 @@ class NewSessionForm {
$form=' $form='
<div id="operation_msg" class="operation_msg"> </div> <div id="operation_msg" class="operation_msg"> </div>
<form id="new_session_form" name="new_session_form" action="eventos.php.php" method="POST"> <form id="session_form" name="session_form" action="eventos.php" method="POST">
<input type="hidden" id="film_id" name="film_id" value=""/>
<input type="hidden" id="original_hall" name="film_id" value=""/>
<input type="hidden" id="original_date" name="film_id" value=""/>
<input type="hidden" id="original_start_time" name="film_id" value=""/>
<div id="global_group" class="form_group"></div> <div id="global_group" class="form_group"></div>
<fieldset> <fieldset>
<legend>Datos</legend> <legend>Datos</legend>
@ -47,11 +53,14 @@ class NewSessionForm {
</div> </div>
</fieldset> </fieldset>
<input type="reset" id="reset" value="Limpiar Campos" > <input type="reset" id="reset" value="Limpiar Campos" >
<input type="submit" id="submit" name="sumbit" class="primary" value="Crear" /> <input type="submit" id="sumbit_new" name="sumbit_new" class="sumbit" value="Añadir" />
<div class="two-inputs-line" id="edit_inputs">
<input type="submit" id="sumbit_edit" name="sumbit_edit" class="sumbit" value="Editar" />
<input type="submit" id="submit_del" name="submit_del" class="black button" value="Borrar" />
</div>
<div id="film_msg_group" class="form_group"> </div> <div id="film_msg_group" class="form_group"> </div>
<div id="film_group" class="form_group"> <div id="film_group" class="form_group">
<div class="code showtimes"> <div class="code showtimes">
<input type="hidden" id="film_id" name="film_id" value=""/>
<h2 id="film_title"> titulo </h2> <h2 id="film_title"> titulo </h2>
<hr /> <hr />
<div class="img_desc"> <div class="img_desc">
@ -86,7 +95,8 @@ class NewSessionForm {
$form.=' $form.='
</ul> </ul>
</div> </div>
</form>'; </form>
';
return $form; return $form;
} }

View File

@ -0,0 +1,57 @@
<?php
$errors = [];
$data = [];
if (empty($_POST['price']) || $_POST['price'] <= 0 ) {
$errors['price'] = 'El precio no puede ser 0.';
}
if (empty($_POST['format'])) {
$errors['format'] = 'El formato no puede estar vacio. Ej: 3D, 2D, voz original';
}
if (empty($_POST['hall']) || $_POST['hall']<=0 ) {
$errors['hall'] = 'La sala no puede ser 0 o menor';
}
if (empty($_POST['startDate'])) {
$errors['startDate'] = 'Las sesiones tienen que empezar algun dia.';
}
if (empty($_POST['endDate'])) {
$errors['endDate'] = 'Las sesiones tienen que teminar algun dia.';
}
if (!empty($_POST['startDate']) && !empty($_POST['endDate'])) {
$start = strtotime($_POST['startDate']);
$end = strtotime($_POST['endDate']);
$start = date('Y-m-d', $start);
$end = date('Y-m-d', $end);
if($start >= $end){
$errors['date'] = 'La fecha inicial no puede ser antes o el mismo dia que la final.';
}
}
if (empty($_POST['startHour'])) {
$errors['startHour'] = 'Es necesario escoger el horario de la sesion.';
}
if (!empty($errors)){
error_log("creamos una sesion, wahoo");
Session::create_session("1", $_POST['hall'], $_POST['startHour'], $_POST['startDate'],
"1",$_POST['price'], $_POST['format'],"0");
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
}
echo json_encode($data);

View File

@ -23,8 +23,10 @@ $(document).ready(function(){
selectable:true, selectable:true,
selectHelper:true, selectHelper:true,
timeFormat: 'H:mm', timeFormat: 'H:mm',
select: function(start, end, allDay) select: function(start, end, allDay)
{ {
$(modal).fadeIn(); $(modal).fadeIn();
var x = document.getElementById("film_group"); var x = document.getElementById("film_group");
@ -33,58 +35,14 @@ $(document).ready(function(){
x = document.getElementById("film_list"); x = document.getElementById("film_list");
x.style.display = "block"; x.style.display = "block";
document.getElementById("hall").value = document.getElementById("hall_selector").value; document.getElementById("hall").value = document.getElementById("hall_selector").value;
document.getElementById("startDate").value = $.fullCalendar.formatDate( start, "Y-MM-DD" ); document.getElementById("startDate").value = $.fullCalendar.formatDate( start, "Y-MM-DD" );
document.getElementById("endDate").value = $.fullCalendar.formatDate( end, "Y-MM-DD" ); document.getElementById("endDate").value = $.fullCalendar.formatDate( end, "Y-MM-DD" );
document.getElementById("sumbit_new").style.display = "block";
/* document.getElementById("edit_inputs").style.display = "none";
var e = {
"date" : $.fullCalendar.formatDate(allDay,"Y-MM-DD"),
"start" : $.fullCalendar.formatDate(start, "HH:mm"),
"end" : $.fullCalendar.formatDate(end, "HH:mm")
};
$.ajax({
url:"eventos.php",
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(e),
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
}
})*/
}, },
editable:true, editable:true,
eventResize:function(event)
{
var e = {
"id" : event.id,
"userId": event.userId,
"start" : $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss"),
"end" : $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss"),
"title" : event.title
};
$.ajax({
url:"eventos.php?idEvento="+event.id,
type:"PUT",
contentType: 'application/json; charset=utf-8',
dataType:"json",
data:JSON.stringify(e),
success:function(){
calendar.fullCalendar('refetchEvents');
alert('Event Update');
}
})
},
eventDrop:function(event) eventDrop:function(event)
{ {
var e = { var e = {
@ -95,7 +53,7 @@ $(document).ready(function(){
"title" : event.title "title" : event.title
}; };
$.ajax({ $.ajax({
url:"eventos.php?idEvento="+event.id, url:"eventos.php?idEvento="+event.id+"resize=true",
contentType: 'application/json; charset=utf-8', contentType: 'application/json; charset=utf-8',
dataType: "json", dataType: "json",
type:"PUT", type:"PUT",
@ -107,27 +65,37 @@ $(document).ready(function(){
} }
}); });
}, },
eventClick:function(event) eventClick:function(event)
{ {
if(confirm("Are you sure you want to remove it?")) $(modal).fadeIn();
{
var id = event.id; var x = document.getElementById("film_group");
$.ajax({ x.style.display = "block";
url:"eventos.php?idEvento="+id,
contentType: 'application/json; charset=utf-8', x = document.getElementById("film_list");
dataType: "json", x.style.display = "none";
type:"DELETE",
success:function() document.getElementById("hall").value = document.getElementById("hall_selector").value;
{ document.getElementById("startDate").value = $.fullCalendar.formatDate( event.start, "Y-MM-DD" );
calendar.fullCalendar('refetchEvents'); document.getElementById("endDate").value = $.fullCalendar.formatDate( event.end, "Y-MM-DD" );
alert("Event Removed"); document.getElementById("price").value = event.seat_price;
}, document.getElementById("format").value = event.format;
error: function(XMLHttpRequest, textStatus, errorThrown) { document.getElementById("startHour").value = event.start_time;
alert("Status: " + textStatus); alert("Error: " + errorThrown);
} document.getElementById("original_hall").value = document.getElementById("hall_selector").value;
}) document.getElementById("original_start_time").value = event.start_time;
} document.getElementById("original_date").value = $.fullCalendar.formatDate( event.start, "Y-MM-DD" );
document.getElementById("film_title").innerHTML = event.film.tittle;
document.getElementById("film_lan").innerHTML = event.film.language;
document.getElementById("film_dur").innerHTML = event.film.duration+" min";
document.getElementById("film_img").src = "../img/films/"+event.film.img;
document.getElementById("film_desc").innerHTML = event.film.description;
document.getElementById("film_id").value = event.film.idfilm;
document.getElementById("sumbit_new").style.display = "none";
document.getElementById("edit_inputs").style.display = "grid";
}, },
}); });
@ -158,14 +126,17 @@ $(document).ready(function(){
var success = document.getElementById("success"); var success = document.getElementById("success");
if(success){ if(success){
calendar.fullCalendar('refetchEvents'); calendar.fullCalendar('refetchEvents');
calendar.fullCalendar('reren');
success.style.display = "none"; success.style.display = "none";
document.getElementById("new_session_form").style.display = "block"; document.getElementById("session_form").style.display = "block";
document.getElementById("price").value = ""; document.getElementById("price").value = "";
document.getElementById("format").value = ""; document.getElementById("format").value = "";
document.getElementById("film_id").value = ""; document.getElementById("film_id").value = "";
document.getElementById("startHour").value =""; document.getElementById("startHour").value ="";
} }
$(".form_group").removeClass("has_error");
$(".help_block").remove();
}); });
} }
}); });

View File

@ -1,37 +1,106 @@
$(document).ready(function () { $(document).ready(function () {
$("form#new_session_form").on('submit', function(e){ //New form session
$('#sumbit_new').click( function(e) {
$(".form_group").removeClass("has_error");
$(".help_block").remove();
$(".form_group").removeClass("has_error"); var formData = {
$(".help_block").remove(); price: $("#price").val(),
format: $("#format").val(),
var formData = { hall: $("#hall").val(),
price: $("#price").val(), startDate: $("#startDate").val(),
format: $("#format").val(), endDate: $("#endDate").val(),
hall: $("#hall").val(), startHour: $("#startHour").val(),
startDate: $("#startDate").val(), idFilm: $("#film_id").val(),
endDate: $("#endDate").val(), };
startHour: $("#startHour").val(),
idFilm: $("#film_id").val(), $.ajax({
}; type: "POST",
url:"eventos.php",
$.ajax({ contentType: 'application/json; charset=utf-8',
type: "POST", dataType: "json",
url:"eventos.php", data:JSON.stringify(formData),
contentType: 'application/json; charset=utf-8', encode: true,
dataType: "json", }).done(function (data) {
data:JSON.stringify(formData), console.log(data);
encode: true, checkErrors(data,"session_form");
}).done(function (data) { })
console.log(data); .fail(function (jqXHR, textStatus) {
checkErrors(data,"new_session_form"); $("form#session_form").html(
}) '<div class="alert alert-danger">Could not reach server, please try again later. '+textStatus+'</div>'
.fail(function (jqXHR, textStatus) { );
$("form#new_session_form").html(
'<div class="alert alert-danger">Could not reach server, please try again later. '+textStatus+'</div>'
);
}); });
e.preventDefault();
});
//Edit session
$('#sumbit_edit').click( function(e) {
$(".form_group").removeClass("has_error");
$(".help_block").remove();
var formData = {
price: $("#price").val(),
format: $("#format").val(),
hall: $("#hall").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
startHour: $("#startHour").val(),
idFilm: $("#film_id").val(),
og_hall: $("#original_hall").val(),
og_date: $("#original_date").val(),
og_start: $("#original_start_time").val(),
};
console.log(formData);
$.ajax({
type: "PUT",
url:"eventos.php",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(formData),
encode: true,
}).done(function (data) {
console.log(data);
checkErrors(data,"session_form");
})
.fail(function (jqXHR, textStatus) {
$("form#session_form").html(
'<div class="alert alert-danger">Could not reach server, please try again later. '+textStatus+'</div>'
);
});
e.preventDefault();
});
/*
$('#sumbit_del').click( function(e) {
$(".form_group").removeClass("has_error");
$(".help_block").remove();
var formData = {
og_hall: $("#original_hall").val(),
og_date: $("#original_date").val(),
og_start: $("#original_start_time").val(),
};
$.ajax({
type: "DELETE",
url:"eventos.php",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(formData),
encode: true,
}).done(function (data) {
console.log(data);
checkErrors(data,"session_form");
})
.fail(function (jqXHR, textStatus) {
$("form#session_form").html(
'<div class="alert alert-danger">Could not reach server, please try again later. '+textStatus+'</div>'
);
});
e.preventDefault();
});*/
function checkErrors(data,formname) { function checkErrors(data,formname) {
if (!data.success) { if (!data.success) {
if (data.errors.price) { if (data.errors.price) {
@ -89,18 +158,16 @@ $(document).ready(function () {
); );
} }
} else { } else {
$("#operation_msg").addClass("has_no_error"); $("#operation_msg").addClass("has_no_error");
$("#operation_msg").append( $("#operation_msg").append(
'<div class="alert alert-success" id="success">' + data.message + "</div>" '<div class="alert alert-success" id="success">' + data.message + "</div>"
); );
document.getElementById(formname).style.display = "none"; document.getElementById("session_form").style.display = "none";
}
} }
e.preventDefault();
}); }
$('.film_button').bind('click', function(e) { $('.film_button').bind('click', function(e) {
var id = $(this).attr('id'); var id = $(this).attr('id');
@ -116,7 +183,6 @@ $(document).ready(function () {
var dur = document.getElementById("dur"+id); var dur = document.getElementById("dur"+id);
document.getElementById("film_dur").innerHTML = dur.innerHTML; document.getElementById("film_dur").innerHTML = dur.innerHTML;
var img = document.getElementById("img"+id); var img = document.getElementById("img"+id);
document.getElementById("film_img").src = "../img/films/"+img.value; document.getElementById("film_img").src = "../img/films/"+img.value;