Commit 0a9b0608 by Juan Montilla Committed by Manuel Ruiz Toribio

ajax

parent 83dd03bb
......@@ -38,6 +38,8 @@ $routes->match(['get', 'post'], '/registerAjax', [User::class, 'registerAjax']);
$routes->match(['get'], '/home', [User::class, 'user_ok']);
$routes->get('/recipe/(:num)', 'RecipesController::view_recipe/$1');
// Ruta para obtener una imagen de una receta dado un id
$routes->get('recipe/image/(:num)', 'RecipesController::show_image/$1');
......@@ -46,15 +48,19 @@ $routes->get('/insert_recipe', 'InsertRecipeController::index');
$routes->match(['get', 'post'], '/search_ingredient', 'InsertRecipeController::search_ingredient');
$routes->post('/insert_recipe', 'InsertRecipeController::insert_recipe');
// Ruta para la búsqueda de recetas
$routes->match(['get', 'post'], '/search_recipe', 'RecipesController::search_recipe');
$routes->post('filter_recipes', 'RecipesController::get_filtered_recipes');
$routes->get('login','Pages::viewLogin');
$routes->get('users','User::list');
$routes->get('home','Pages::prueba');
$routes->get('(:segment)', 'Home::index');
$routes->get('/recipe/(:num)', 'RecipesController::view_recipe/$1');
......
......@@ -25,7 +25,7 @@ class RecipesController extends Controller
];
return view('templates/header', $data)
. view('pages/recipe_view', $data)
. view('pages/recipe_view')
. view('templates/footer');
}
......@@ -45,25 +45,26 @@ class RecipesController extends Controller
}
}
//public function search_recipe() {
// Obtener la consulta de búsqueda desde el formulario
// $query = $this->request->getVar('query');
// Cargar el modelo de ingredientes (si no lo has hecho)
//$recipesModel = new \App\Models\RecipesModel();
// Buscar ingredientes en la base de datos que coincidan con la consulta
// $recipes = $recipesModel->search_recipe($query);
// Devolver los ingredientes coincidentes en formato JSON
// return $this->response->setJSON($recipes);
// }
public function search_recipe()
{
$query = $this->request->getVar('query');
$recipesModel = new \App\Models\RecipesModel();
$recipes = $recipesModel->search_recipe($query);
$recipes = $recipesModel->searchRecipe($query);
return $this->response->setJSON($recipes);
}
// En tu controlador de recetas
public function get_filtered_recipes() {
$recipesModel = new \App\Models\RecipesModel();
$vegan = $this->request->getPost('is_vegan') == "true" ? true : false;
$country = $this->request->getPost('origin');
$season = $this->request->getPost('season');
$filtered_recipes = $recipesModel->get_filtered_recipes($vegan, $country, $season);
return $this->response->setJSON($filtered_recipes);
}
}
\ No newline at end of file
......@@ -3,7 +3,7 @@ namespace App\Models;
use CodeIgniter\Model;
class recipesModel extends Model
class RecipesModel extends Model
{
protected $table = 'recipes';
protected $primaryKey = 'id';
......@@ -11,7 +11,7 @@ class recipesModel extends Model
protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods
protected $allowedFields = ['id', 'name', 'season','origin','photo','is_vegan','description','instructions','link'];
protected $allowedFields = ['id', 'name', 'season', 'origin', 'photo', 'is_vegan', 'description', 'instructions', 'link'];
protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...)
protected $validationRules = [];
......@@ -35,7 +35,8 @@ class recipesModel extends Model
return $this->insert($data);
}
public function get_recipe_ingredients($recipe_id) {
public function get_recipe_ingredients($recipe_id)
{
$builder = $this->db->table('recipes_ingredient');
$builder->select('ingredient.name, ingredient.icon, recipes_ingredient.amount');
$builder->join('ingredient', 'recipes_ingredient.id_ingredient = ingredient.id');
......@@ -43,21 +44,40 @@ class recipesModel extends Model
$query = $builder->get();
return $query->getResult();
}
/* public function search_recipe($query)
public function searchRecipe($query)
{
if ($query) {
// Seleccionar todas las columnas excepto 'photo'
$this->select('id, name, season, origin, is_vegan, description, instructions, link');
return $this->like('name', $query)->findAll();
}
return [];
} */
}
public function search_recipe($query)
{
if ($query) {
return $this->like('name', $query)->findAll();
public function get_filtered_recipes($vegan, $country, $season) {
$builder = $this->db->table('recipes');
if ($vegan) {
$builder->where('is_vegan', true);
}
return [];
if (!empty($country)) {
$builder->where('origin', $country);
}
if (!empty($season)) {
$builder->where('season', $season);
}
$query = $builder->get();
return $query->getResult();
}
}
\ No newline at end of file
......@@ -42,9 +42,8 @@
<select id="origin" name="origin" class="form-control">
<option value="Española">Española</option>
<option value="Francesa">Francesa</option>
<option value="Italiana">Italiana</option>
<option value="Italiana">Japonesa</option>
<option value="Mexiana">Mexicana</option>
<option value="Americana">Americana</option>
<option value="China">China</option>
<option value="India">India</option>
</select>
......
<?php
function getYoutubeVideoId($url) {
function getYoutubeVideoId($url)
{
$pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i';
preg_match($pattern, $url, $matches);
return isset($matches[1]) ? $matches[1] : null;
......@@ -7,112 +8,124 @@ function getYoutubeVideoId($url) {
?>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
max-width: 960px;
margin: 0 auto;
padding: 20px;
}
.recipe-header {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 30px;
}
.recipe-header img {
width: 100%;
max-width: 600px;
height: auto;
object-fit: cover;
border-radius: 8px;
}
.ingredient-list {
display: flex;
flex-wrap: wrap;
list-style-type: none;
padding: 0;
margin: 0;
margin-bottom: 30px;
}
.ingredient-item {
display: flex;
align-items: center;
width: 50%;
padding: 5px 0;
}
.ingredient-item img {
width: 30px;
height: 30px;
margin-right: 10px;
}
.instructions {
white-space: pre-line;
}
.video-container {
position: relative;
padding-bottom: 56.25%; /* Relación de aspecto 16:9 */
height: 0;
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<main id="mainview" class="mainview">
<section class="section dashboard">
<div class="container">
<div class="recipe-header">
<h1>Receta:</h1>
<h1><?php echo $recipe->name; ?></h1>
<img src="<?php echo base_url('recipe/image/' . $recipe->id); ?>" alt="<?php echo $recipe->name; ?>" />
</div>
<p><?php echo $recipe->description; ?></p>
<h2>Ingredientes</h2>
<ul class="ingredient-list">
<?php foreach ($ingredients as $ingredient) { ?>
<li class="ingredient-item">
<img src="../imagenes/ingredientes/<?php echo $ingredient->icon; ?>" alt="<?php echo $ingredient->name; ?>" />
<span><?php echo $ingredient->name; ?>: <?php echo $ingredient->amount; ?></span>
</li>
<?php } ?>
</ul>
<h2>Instrucciones</h2>
<p class="instructions"><?php echo $recipe->instructions; ?></p>
<?php if (!empty($recipe->link)): ?>
<?php $videoId = getYoutubeVideoId($recipe->link); ?>
<?php if ($videoId): ?>
<h2>Video de la receta</h2>
<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $videoId; ?>" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
max-width: 960px;
margin: 0 auto;
padding: 20px;
}
.recipe-header {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 30px;
}
.recipe-header img {
width: 100%;
max-width: 600px;
height: auto;
object-fit: cover;
border-radius: 8px;
}
.ingredient-list {
display: flex;
flex-wrap: wrap;
list-style-type: none;
padding: 0;
margin: 0;
margin-bottom: 30px;
}
.ingredient-item {
display: flex;
align-items: center;
width: 50%;
padding: 5px 0;
}
.ingredient-item img {
width: 30px;
height: 30px;
margin-right: 10px;
}
.instructions {
white-space: pre-line;
}
.video-container {
position: relative;
padding-bottom: 56.25%;
/* Relación de aspecto 16:9 */
height: 0;
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<main id="main" class="main">
<section class="section dashboard">
<div class="container">
<div class="recipe-header">
<h1>
<?php echo $recipe->name; ?>
</h1>
<img src="<?php echo base_url('recipe/image/' . $recipe->id); ?>" alt="<?php echo $recipe->name; ?>" />
</div>
<p>
<?php echo $recipe->description; ?>
</p>
<h2>Ingredientes</h2>
<ul class="ingredient-list">
<?php foreach ($ingredients as $ingredient) { ?>
<li class="ingredient-item">
<img src="../imagenes/ingredientes/<?php echo $ingredient->icon; ?>"
alt="<?php echo $ingredient->name; ?>" />
<span>
<?php echo $ingredient->name; ?>:
<?php echo $ingredient->amount; ?>
</span>
</li>
<?php } ?>
</ul>
<h2>Instrucciones</h2>
<p class="instructions">
<?php echo $recipe->instructions; ?>
</p>
<?php if (!empty($recipe->link)): ?>
<?php $videoId = getYoutubeVideoId($recipe->link); ?>
<?php if ($videoId): ?>
<h2>Video de la receta</h2>
<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $videoId; ?>"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
</div>
</div>
</section>
</main><!-- End #main -->
\ No newline at end of file
</main><!-- End #main -->
......@@ -32,8 +32,8 @@
<link href="<?= base_url("css/style.css") ?>" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"
integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</head>
......@@ -55,15 +55,15 @@
<i class="bi bi-list toggle-sidebar-btn"></i>
</div><!-- End Logo -->
<!-- Barra de búsqueda -->
<div class="search-bar">
<form class="search-form d-flex align-items-center" method="POST" action="#">
<input type="text" id="search-query" name="query" placeholder="Buscar por receta..."
title="Enter search keyword">
</form>
<div id="recipe_dropdown" class="recipe-dropdown">
<ul id="recipe_list" class="recipe-list list-unstyled"></ul>
</div>
</div>
<form class="search-form d-flex align-items-center" method="POST" action="#">
<input type="text" id="search-query" name="query" placeholder="Buscar por receta..."
title="Enter search keyword" >
</form>
<ul id="recipe_list" class="ingredients-list list-unstyled"></ul>
</div>
<!-- Fin barra de búsqueda -->
......@@ -154,4 +154,165 @@
</ul>
</nav><!-- End Icons Navigation -->
</header><!-- End Header -->
\ No newline at end of file
</header><!-- End Header -->
<!-- ======= Sidebar ======= -->
<aside id="sidebar" class="sidebar">
<ul class="sidebar-nav" id="sidebar-nav">
<li class="nav-item">
<a class="nav-link " href="index.html">
<i class="bi bi-grid"></i>
<span>Recetas</span>
</a>
</li><!-- End Dashboard Nav -->
<!-- Filtro 1-->
<li class="nav-item">
<a class="nav-link collapsed" data-bs-target="#tables-nav" data-bs-toggle="collapse" href="#">
<i class="bi bi-layout-text-window-reverse"></i><span>Filtro Vegano</span><i
class="bi bi-chevron-down ms-auto"></i>
</a>
<ul id="tables-nav" class="nav-content collapse " data-bs-parent="#sidebar-nav">
<!--Contenido del dropdown-->
<ul class="vegan-cboxtags">
<li>
<input type="checkbox" id="checkboxOne" value="Order one" onchange="updateRecipeList()">
<label for="checkboxOne">Recetas Veganas </label>
</li>
</ul>
</ul>
</li><!-- Fin Filtro 1 -->
<!-- Filtro 1-->
<li class="nav-item">
<a class="nav-link collapsed" data-bs-target="#tables-nav2" data-bs-toggle="collapse" href="#">
<i class="bi bi-layout-text-window-reverse"></i><span>Filtro 2</span><i
class="bi bi-chevron-down ms-auto"></i>
</a>
<ul id="tables-nav2" class="nav-content collapse " data-bs-parent="#sidebar-nav">
<!--Contenido del dropdown-->
<ul class="indian-cboxtags">
<li>
<input type="checkbox" id="checkboxFour" value="Order four" onchange="updateRecipeList()">
<label for="checkboxFour">India </label>
</li>
</ul>
<ul class="french-cboxtags">
<li>
<input type="checkbox" id="checkboxFive" value="Order five" onchange="updateRecipeList()">
<label for="checkboxFive">Francia </label>
</li>
</ul>
<ul class="chinese-cboxtags">
<li>
<input type="checkbox" id="checkboxSix" value="Order six" onchange="updateRecipeList()">
<label for="checkboxSix">China </label>
</li>
</ul>
<ul class="mexican-cboxtags">
<li>
<input type="checkbox" id="checkboxSeven" value="Order seven" onchange="updateRecipeList()">
<label for="checkboxSeven">México </label>
</li>
</ul>
<ul class="spanish-cboxtags">
<li>
<input type="checkbox" id="checkboxEight" value="Order eigth" onchange="updateRecipeList()">
<label for="checkboxEight">España </label>
</li>
</ul>
<ul class="japanese-cboxtags">
<li>
<input type="checkbox" id="checkboxNine" value="Order nine" onchange="updateRecipeList()">
<label for="checkboxNine">Japón </label>
</li>
</ul>
</ul>
</li><!-- Fin Filtro 1 -->
<li class="nav-item">
<a class="nav-link collapsed" data-bs-target="#tables-nav3" data-bs-toggle="collapse" href="#">
<i class="bi bi-layout-text-window-reverse"></i><span>Estaciones</span><i
class="bi bi-chevron-down ms-auto"></i>
</a>
<ul id="tables-nav3" class="nav-content collapse " data-bs-parent="#sidebar-nav">
<!--Contenido del dropdown-->
<ul class="winter-cboxtags">
<li>
<input type="checkbox" id="checkboxTen" value="Order ten" onchange="updateRecipeList()">
<label for="checkboxTen">Invierno </label>
</li>
</ul>
<ul class="spring-cboxtags">
<li>
<input type="checkbox" id="checkboxEleven" value="Order eleven" onchange="updateRecipeList()">
<label for="checkboxEleven">Primavera </label>
</li>
</ul>
<ul class="summer-cboxtags">
<li>
<input type="checkbox" id="checkboxTwelve" value="Order twelve" onchange="updateRecipeList()">
<label for="checkboxTwelve">Verano </label>
</li>
</ul>
<ul class="autumn-cboxtags">
<li>
<input type="checkbox" id="checkbox13" value="Order 13" onchange="updateRecipeList()">
<label for="checkbox13">Otoño </label>
</li>
</ul>
</ul>
</li><!-- Fin Filtro 1 -->
<li class="nav-item">
<a class="nav-link collapsed" href="/insert_recipe">
<i class="bi bi-file-earmark"></i>
<span>Subir receta</span>
</a>
</li><!-- End Profile Page Nav -->
<li class="nav-item">
<a class="nav-link collapsed" href="https://www.instagram.com/salvaperfectti/">
<i class="bi bi-envelope"></i>
<span>Contacto</span>
</a>
</li><!-- End Contact Page Nav -->
<li class="nav-item">
<a class="nav-link collapsed" href="/login">
<i class="bi bi-box-arrow-in-right"></i>
<span>Registro/Login</span>
</a>
</li><!-- End Login Page Nav -->
<li class="nav-item">
<a class="nav-link collapsed" href="http://www.homerswebpage.com/">
<i class="bi bi-dash-circle"></i>
<span>Error 404</span>
</a>
</li><!-- End Error 404 Page Nav -->
</ul>
</aside><!-- End Sidebar-->
\ No newline at end of file
......@@ -360,6 +360,26 @@ h6 {
.header .search-bar {
min-width: 360px;
padding: 0 20px;
position: relative;
}
#recipe_list {
position: absolute;
top: 100%;
left: 0;
z-index: 1;
width: 100%;
max-height: 200px;
overflow-y: auto;
background-color: #fff;
border-top: none;
border-radius: 0 0 .25rem .25rem;
padding: 0;
margin: 0;
}
.recipe-item {
cursor: pointer;
}
@media (max-width: 1199px) {
......@@ -789,10 +809,7 @@ h6 {
}
/* Info Cards */
.dashboard .info-card {
padding-bottom: 10px;
}
s
.dashboard .info-card h6 {
font-size: 28px;
color: #012970;
......@@ -904,12 +921,6 @@ h6 {
padding-left: 0;
}
.recipe-card-link {
display: block;
text-decoration: none;
color: inherit;
}
.dashboard .news p {
font-size: 14px;
color: #777777;
......
......@@ -11,21 +11,21 @@ const recipeForm = document.querySelector("form.my-form");
recipeForm.addEventListener("submit", function (event) {
const selectedIngredients = Array.from(document.querySelectorAll(".selected-ingredient"));
const ingredientsData = selectedIngredients.map((ingredientElem) => {
return {
id: ingredientElem.dataset.ingredientId,
amount: ingredientElem.querySelector(".ingredient-amount").textContent,
};
return {
id: ingredientElem.dataset.ingredientId,
amount: ingredientElem.querySelector(".ingredient-amount").textContent,
};
});
const hiddenInput = document.createElement("input");
hiddenInput.type = "hidden";
hiddenInput.name = "selected_ingredients";
hiddenInput.value = JSON.stringify(ingredientsData);
recipeForm.appendChild(hiddenInput);
});
});
// Array para almacenar palabras clave seleccionadas
let ingredients = [];
......@@ -35,7 +35,7 @@ function searchIngredients(query) {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest' // Añadir esta línea
'X-Requested-With': 'XMLHttpRequest'
},
body: 'query=' + encodeURIComponent(query)
})
......@@ -109,38 +109,38 @@ function removeIngredient(ingredient) {
function updateSelectedIngredients() {
// Limpiar el campo de selección
selectedIngredients.innerHTML = '';
// Agregar cada ingrediente seleccionado al campo de selección
ingredients.forEach(function (ingredient) {
const ingredientElement = document.createElement('div');
ingredientElement.classList.add('selected-ingredient');
ingredientElement.setAttribute('data-ingredient-id', ingredient.id);
// Crear el elemento de imagen para el icono del ingrediente
const iconElement = document.createElement('img');
iconElement.classList.add('ingredient-icon');
iconElement.src = '../imagenes/ingredientes/' + ingredient.icon;
ingredientElement.appendChild(iconElement);
// Agregar el nombre del ingrediente y la cantidad
const ingredientNameAndQuantity = document.createElement('span');
ingredientNameAndQuantity.textContent = `${ingredient.name} (${ingredient.quantity})`;
ingredientNameAndQuantity.classList.add('ingredient-amount');
ingredientElement.appendChild(ingredientNameAndQuantity);
// Agregar el botón para eliminar el ingrediente
const removeBtn = document.createElement('button');
removeBtn.classList.add('btn', 'btn-danger', 'btn-sm');
removeBtn.textContent = 'x';
removeBtn.addEventListener('click', function () {
removeIngredient(ingredient);
});
ingredientElement.appendChild(removeBtn);
selectedIngredients.appendChild(ingredientElement);
const ingredientElement = document.createElement('div');
ingredientElement.classList.add('selected-ingredient');
ingredientElement.setAttribute('data-ingredient-id', ingredient.id);
// Crear el elemento de imagen para el icono del ingrediente
const iconElement = document.createElement('img');
iconElement.classList.add('ingredient-icon');
iconElement.src = '../imagenes/ingredientes/' + ingredient.icon;
ingredientElement.appendChild(iconElement);
// Agregar el nombre del ingrediente y la cantidad
const ingredientNameAndQuantity = document.createElement('span');
ingredientNameAndQuantity.textContent = `${ingredient.name} (${ingredient.quantity})`;
ingredientNameAndQuantity.classList.add('ingredient-amount');
ingredientElement.appendChild(ingredientNameAndQuantity);
// Agregar el botón para eliminar el ingrediente
const removeBtn = document.createElement('button');
removeBtn.classList.add('btn', 'btn-danger', 'btn-sm');
removeBtn.textContent = 'x';
removeBtn.addEventListener('click', function () {
removeIngredient(ingredient);
});
ingredientElement.appendChild(removeBtn);
selectedIngredients.appendChild(ingredientElement);
});
}
}
......@@ -154,43 +154,43 @@ ingredientSearch.addEventListener('input', function (event) {
var inputPhoto = document.getElementById('photo');
var imageUploadContainer = document.querySelector('.image-upload-container');
inputPhoto.addEventListener('change', function(event) {
inputPhoto.addEventListener('change', function (event) {
displayImagePreview(event.target.files[0]);
});
imageUploadContainer.addEventListener('dragover', function(event) {
});
imageUploadContainer.addEventListener('dragover', function (event) {
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = 'copy';
});
imageUploadContainer.addEventListener('drop', function(event) {
});
imageUploadContainer.addEventListener('drop', function (event) {
event.preventDefault();
event.stopPropagation();
if (event.dataTransfer.files.length > 0) {
displayImagePreview(event.dataTransfer.files[0]);
inputPhoto.files = event.dataTransfer.files;
displayImagePreview(event.dataTransfer.files[0]);
inputPhoto.files = event.dataTransfer.files;
}
});
function displayImagePreview(file) {
});
function displayImagePreview(file) {
var reader = new FileReader();
reader.onload = function() {
var output = document.getElementById('image-preview');
output.src = reader.result;
output.style.display = 'block';
reader.onload = function () {
var output = document.getElementById('image-preview');
output.src = reader.result;
output.style.display = 'block';
}
reader.readAsDataURL(file);
}
}
document.getElementById('photo').addEventListener('change', function(event) {
document.getElementById('photo').addEventListener('change', function (event) {
var reader = new FileReader();
reader.onload = function() {
var output = document.getElementById('image-preview');
output.src = reader.result;
output.style.display = 'block';
reader.onload = function () {
var output = document.getElementById('image-preview');
output.src = reader.result;
output.style.display = 'block';
}
reader.readAsDataURL(event.target.files[0]);
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment