Using PHP in javascript’s IF Statement

This is a post about what you should not do. I spent like 3 hours trying to make it work until I realised it would never do it.  This was my code

 if (ciudad === '') {
 $("#menu_datos_personales").append("<span class='glyphicon glyphicon-remove pull-right'></span>");
 } else {
 $("#menu_datos_personales").append("<span class='glyphicon glyphicon-ok pull-right'></span>");
 <?php $_SESSION['datos_personales_guardados'] = true; ?>

After a quick search, I learned that the PHP code was already executed in the server before sending the page to the browser. So, in the browser, the PHP was not there any more when the javascript function would run. More info?


Changing between login and sign up form

I made the typical sign up / login page that shows by default the sign up form. When you click on “I have already an account”, the sign up form will disappear and the login form will appear using javascript. I got the problem however on how to make the login form visible by default, as soon as you get to the page, login.php, in this case coming from a link.

To do this, I added a variable in the link, after reading this tutorial. So, in this case, the link would be http://www.login.php?action=login.

In javascript, what you have to say is something like if action = “login”, make the sign up form disappear and the login form appear.

 var action = "<?php echo $_GET["action"]; ?>";
 if (action = "login") {
 $("#error_login").css("color", "red"); 

There is another case I also had, when you, instead of coming from a link, come  from another php. This happens when you sign up with an email, but this email has already an account associated (which is checked in another php, e.g. login2.php) In that moment, you send the user back to login.php, but you want to show him the login form, not the sign up form.

To do this, you create in login2.php an error messsage inside a $_SESSION variable. In login.php, similar to previous case, you say that if that variable exists, login form has to be visible.


$query2 = "SELECT `email` FROM `profesional_login` where `email`='$email'";
$result2 = mysql_query($query2);
$numResults = mysql_num_rows($result2);
if ($numResults>=1) {
 $_SESSION['error_email_existe'] = "Ese email ya tiene una cuenta asociada. Por favor, acceda a su cuenta.";
 header('Location: login.php');


var error = "<?php echo $_SESSION['error_email_existe'];?>";
 if (error != "") {
 $("#error_login").css("color", "red");

Populate database

For my project I wanted to populate the website with picture and other personal details from different people. The data did not have to be real (actually should not be real!), I just want to make the web look real.

First approach tried, create mysql database with randomly generated data. After a couple of trials in google, relevant results appear under query “creating database random name mysql”. After checking several, I sticked to the first one, . With it, I could fill the rows for the name, last name, address, phone number and user_id. It also generates random text with typical Lorem Ipsum words, which I firstly used to populate the rows for the opinions and descriptions.

For the pictures, after having a look at a couple of possibilities like (using an api) or (not good profile pictures, and also quite repetitive after a while), I decided to use a common avatar picture as a placeholder, to make it simple. In my code, I retrieve the data from the database via php, getting a json that parse as an array in javascript. This is the solution to use a placeholder when there are no pictures (some users had already uploaded one, so I wanted to use these for them instead of the placeholder)

// Call to database (I removed the code inside)
var imagen_json = '<?php ... ?>
// Parsing the json data into a javascript array
var obj = $.parseJSON(imagen_json);
// Getting the id from html where I want to insert the data
var anunciante = document.getElementById("anunciante");
// Looping into the array.
for (var i = 0; i < obj.length; i++) {
 // When the element is empty user did not upload picture), use avatar picture
 if (obj[i].foto === "") {
 obj[i].foto = "z_001.png";
var newBloque = '<img class="img-responsive" src="img/nuevos_profesionales/' + obj[i].foto + '" alt="">'
anunciante.innerHTML += newBloque;


ikeet app: feature to add a new recipe

In the beginning I thought I could leave this feature for later, since I could always paste the recipe directly in the database with phpMyAdmin. However, I had a couple of problems with the formatting of the text. So I decided to build a form in the app that allowed me to add the info, solving any formatting problem with php.

The code in html is the typical one for any form. I wanted the form to have dish title, food type, recipe text and picture loader.

<form action="nueva_receta_upload.php" method="post" enctype="multipart/form-data">
<div class="form-group">
 <label class="sr-only" for="MAX_FILE_SIZE">file size</label>
 <input type="hidden" name="MAX_FILE_SIZE" value="1000000" placeholder="file size" value="<?php echo $row_array['filename'];?>" />

 <div class="form-group">
 <label class="sr-only" for="form_data">file</label>
 <input data-badge="false" class="filestyle" type="file" name="form_data" id="form_data" size="40" placeholder="file" />
 (Para evitar problemas, asegúrate que las fotos tengan un formato .jpg o .png, y un tamaño máximo de 1000KB)

 <div class="form-group">
 <label class="sr-only" for="plato_nombre"></label>
 <textarea type="text" class="form-control" name="plato_nombre" placeholder="Nombre del plato" /></textarea>

 <div class="form-group">
 <label class="sr-only" for="plato_tipo"></label>
 <textarea type="text" class="form-control" name="plato_tipo" placeholder="Tipo de plato" /></textarea>

 <div class="form-group">
 <label class="sr-only" for="plato_receta"></label>
 <textarea type="text" class="form-control" name="plato_receta" placeholder="Escribe la receta" /></textarea>

 <button type="submit" value="submit" class="btn btn-default btn-primary pull-right" >Guardar cambios</button>
 <p> Si tienes alguna duda, contáctanos en</p>

The form points to the php file that will connect with the database



 $plato_nombre = nl2br($_POST['plato_nombre']);
 $plato_receta = nl2br($_POST['plato_receta']);
 $plato_tipo = nl2br($_POST['plato_tipo']);

 // Si ha guardado una foto de un producto, subela al server y guarda el path en la db

 if ($_FILES['form_data']['name']!="") {
 $name = $_FILES['form_data']['name'];
 $target = "images/"; 
 $target = $target . basename( $_FILES['form_data']['name']);
 //Writes the photo to the server 
 move_uploaded_file($_FILES['form_data']['tmp_name'], $target); 

 $result2 = "INSERT INTO `comidas` 
 (`id`, `comida`,`foto`,`tipo`,`receta`) 

 //if data was correctly stored, go to new recipe page. If not, go back to form page
 $last_id = mysql_insert_id($conn);
 } else { 
 header('Location: nueva_receta.php');


Using variables in the code

Everytime I have to use a variable inside the code, I have to try different ways of writing it until I find the correct one. It is difficult for me to remember how to insert it depending on the language (php, html, javascript…) Let´s see if this self-made guide can help me doing it correctly next time in only one time!


– Example 1:

<img src="images/<?php echo $row_array['foto'];?>" ">

– Example 2:

$last_id = mysql_insert_id($conn);


var plato_foto = obj[random].foto;
var menu = '<div><img src="images/' + plato_foto + '" '

As explained in the previous post, the first feature to implement was to suggest a recipe to cook, allowing me to dismiss it if I do not like it, showing me a new one from the database. This new one should of course not be one of the previously dismissed.

To implement this feature, I broke it into small steps:

0) The html


<div class=”container”>

<div id=”plato”>
<div id=”botones”>

<script src=”js/jquery-1.11.0.js”></script>


1) Get content from database

//get info from database and create a json array
var recetas = ‘<?php
strSQL = “SELECT * FROM `comidas`”;
$rs = mysql_query($strSQL);
$json_response = array();
while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
$row_array[‘id’] = $row[‘id’];
$row_array[‘comida’] = $row[‘comida’];
$row_array[‘foto’] = $row[‘foto’];
array_push($json_response,$row_array); }
echo json_encode($json_response);
mysql_close(); ?>;

//via jquery, create array that can be used in javascript
var obj = $.parseJSON(recetas);

2) Get a random element of the array generated

random = Math.floor(Math.random()*obj.length);

I got this answer in stack overflow. To understand better the whole expression, you can always learn what Math.floor and Math.random() specifically do.

3) Show that element inside a div

var plato_dia = obj[random].comida;
var plato_foto = obj[random].foto;
var carousel = document.getElementById(“plato”);
var menu = ‘<div><img src=”images/’ + plato_foto + ‘” style=”width:100%;”></div><h3>’ + plato_dia + ‘</h3>’;
carousel.innerHTML += menu;

//Show two buttons to choose or dismiss the recipe

var botas = ‘<div class=”row” style=”height:100px”><a class=”btn btn-primary btn-danger pull-right” id=”quitar_receta” style=”height:100%; width:50%” href=”#”><span class=”glyphicon glyphicon-remove”></span></a><a class=”btn btn-primary btn-success pull-right” style=”height:100%; width:50%” href=””><span class=”glyphicon glyphicon-ok”></span></a></div><div class=”row”><a class=”btn btn-primary” style=”width:100%” href=””>Elige un plato</a></div>’;

var divbotones = document.getElementById(“botones”);
divbotones.innerHTML += botas;

4) Dismiss recipe and show a new one when clicking on button

$(‘#quitar_receta’).click(function() {
//Remove content in div
$( “#plato” ).empty();
//remove element from array in position “random”
obj.splice(random, 1);
//choose a new random number
random = Math.floor(Math.random()*obj.length);
//insert again the content of that position inside div
var plato_dia2 = obj[random].comida;
var plato_foto2 = obj[random].foto;
var menu2 = ‘<div><img src=”images/’ + plato_foto2 + ‘” style=”width:100%;”></div><h3>’ + plato_dia2 + ‘</h3>’;
carousel.innerHTML += menu2;

> Lessons learned

– Usage of math.floor, math.random and splice javascript methods.

Scope of variables. I was around three days stucked because I had defined first “random” variable as var random = “Math.floor(Math.random()*obj.length);”. This had as consecuence the fact that it was not recognized inside $(‘#quitar_receta’).click(function(), so it removed a different item from the array than the one already shown, which meant that a previously dismissed recipe would be shown again later. The solution to this was to remove the “var” when defining the variable “random”, so the scope would be global instead of local.

ikeet: feature to suggest and dismiss recipes


ikeet: concept for a cooking recipes app

One of my daily “problems” is to choose what to eat. I hate that moment in which my girlfriend asks me “what are we going to eat today?”. This question normally comes in a moment where I do not have the mental peace to think quiet and go through all the dishes you know, specially because I am already annoyed thinking: “fuck, again this moment!”. Sometimes we find quick an answer, normally by choosing a recipe we eat often. Sometimes it gets more frustrating and takes more time. Other times we have time enough to take a step back and go to one of the recipe books or notebooks and have a look, and get the other typical moment:”ey, let’s cook this one, it was really nice! I had completely forgotten it!!”

The other fact of this problem is that I am not a good cooker, mainly because I do not like spending time in cooking, and also because I do not follow a process that would make me better at it. I keep making the same mistakes everytime I cook a dish.

After repeating these two mistakes for years, I decided to tackle it, and create an app that help me choosing what to cook and allow me to get track of the mistakes I make when cooking, so next time I do not repeat them. I made a quick research of existing apps, but decided none of them would suit me, since I wanted to use my own recipes I or my girlfriend have been kind of collecting through the years.

As always, defining the MVP is difficult. Deciding what to build first and what to leave for later is always challenging. I am going to be the main user, and my girlfriend the second, so I used our requirements as first usability research inputs. Based on this, these are the features of the MVP, in order of importance:

1) Inspire me by showing a recipe, and allow me to dismiss it if I do not feel like eating it, and show me a new one.

2) Allow me to search in the database.

3) Allow me to easily add a new recipe.

As a MVP, it should be really simple and quick to build, so I do not miss motivation, adding little by little more complexity and new features in case we use the app.

Of course, there is another part of the app I did not write there: the database. I made a little research to build it automated, but could not find an easy one, so I guess I will do it manually.