Skip to content

Listening for variable changes in JavaScript (Detectar cambios en variable)

JavaScript

 

 

 

You can define an object like this, in which aInternal represents the field a:

x = {
  aInternal: 10,
  aListener: function(val) {},
  set a(val) {
    this.aInternal = val;
    this.aListener(val);
  },
  get a() {
    return this.aInternal;
  },
  registerListener: function(listener) {
    this.aListener = listener;
  }
}

Then you can register a listener using the following:

x.registerListener(function(val) {
  alert("Someone changed the value of x.a to " + val);
});

So whenever anything changes the value of x.a, the listener function will be fired. Running the following line will bring the alert popup:

x.a = 42;

See an example here: https://jsfiddle.net/5o1wf1bn/1/

You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.

Continue reading "Listening for variable changes in JavaScript (Detectar cambios en variable)"

Reemplazar cadenas de caracteres en MySql

DataBase


 

 

 

Para reemplazar una cadena de texto por otra, sin necesidad de estar tupla a tupla:

UPDATE `tabla` SET campo = REPLACE(campo,'texto a buscar','nuevo texto');

Y si por ejemplo queremos actualizar un determinado campo comprendido entre una fecha:

UPDATE `tabla` SET campo = REPLACE(campo,'texto a buscar','nuevo texto') WHERE fecha BETWEEN '2012-06-01' AND '2012-06-31';

L

Continue reading "Reemplazar cadenas de caracteres en MySql"

AJAX DENTRO DE FOR EN JAVASCRIPT

JavaScript


 

 

Código Java Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
  <head>
    <title>Ajax dentro del ciclo for en Java Script</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <script>
      var ids = [1,2,3,4,5];
       
      for(indice = 0; indice < ids.length; indice++){
      // Es importante notar que estamos utilizando jQuery
      $.ajax({
          url: "test.php",
          method: "POST",
          data: { parametro: ids[indice] }
            }).done(function(data) {
               console.log(data);
          });
      }
    </script>
  </body>
</html>
 

Peticiones AJAX dentro del ciclo for en Java Script

Una de las opciones para solucionar este problema es la recursividad, si no están muy familiarizados con este tema los invito al leer el tutorial que explica que es la programación recursiva. Para este caso podemos crear una función que se llama a sí misma dentro de done con el parámetro del índice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
  <head>
    <title>AJAX dentro del ciclo for en Java Script</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <script>
      var ids = [1,2,3,4,5];
       
      function enviar(indice){
        // Es importante notar que estamos utilizando jQuery
        if(indice < ids.length){
          $.ajax({
            url: "test.php",
            method: "POST",
            data: { parametro: ids[indice] }
            }).done(function(data) {
              console.log(data);
              enviar(indice + 1);
          });
        }
      }
      enviar(0);
    </script>
  </body>
</html>

Con el script anterior nos aseguraremos que nuestro código se ejecute de la misma forma (estructural) siempre, donde cada petición AJAX se va a ejecutar una vez que termine la anterior.

Continue reading "AJAX DENTRO DE FOR EN JAVASCRIPT"

IF Shorthand (if corto, if acortado)

Php

 

 

Basic True / False Declaration

$is_admin = ($user['permissions'] == 'admin') ? true : false;

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Conditional Items Message

echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';

Conditional Error Reporting Level

error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT);

Conditional Basepath

echo '<base href="http'.($PAGE_IS_SECURE ? 's' : '').'://mydomain.com" />';

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

Leap Year Check

$is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));

Conditional PHP Redirect

header('Location: '.($valid_login ? '/members/index.php' : 'login.php?errors=1')); exit();
Continue reading "IF Shorthand (if corto, if acortado)"

Configurar VPN RoadWarrior Client-Server

  1. Installed OpenVPN from software center,
  2. goto Gateway → OpenVPN roadwarrior
  3. Checked → Enable roadwarrior server
  4. choosed Username, password and certificate
  5. Mode → Routed mode
  6. Entered desired IP network for VPN
  7. Entered desired Netmask for VPN
  8. [advanced] → checked Push all static routes
  9. [advanced] → DHCP options → enter domain name and local DNS server IP
  10. [Connection parameters] → enter your external IP address / or external dns name
  11. After that I installed LDAP account provider
  12. created new user + password
  13. go back to Gateway → OpenVPN roadwarrior
  14. second tab → Roadwarriors account → Create new
  15. choosed System user → submit
  16. go back to Roadwarriors account → on user use Action and Downloaded listed files
  17. OpenVPN client on Windows/Linux works very well with that
Continue reading "Configurar VPN RoadWarrior Client-Server"

Verificar si key existe en objeto JSON / Check if key exists in JSON object using jQuery

JQuery

 

 

 

if you have an array

var subcategories=[{name:"test",desc:"test"}];

function hasCategory(nameStr) {
        for(let i=0;i<subcategories.length;i++){
            if(subcategories[i].name===nameStr){
                return true;
            }
        }
        return false;
    }

if you have an object

var category={name:"asd",test:""};

if(category.hasOwnProperty('name')){//or category.name!==undefined
   return true;
}else{
   return false;
}

Continue reading "Verificar si key existe en objeto JSON / Check if key exists in JSON object using jQuery"

Close a Modal using the ESC Key? / Cerrar Modal usando ESC

JavaScriptJQuery

 

 

 

$(document).ready(function(){

    $('.modal').modal({show: false, keyboard: false}); // disable keyboard because it conflicts below

    $('.modal').on('show.bs.modal', function (event) {
       //add modal id to array
       modals.push(event.target.id);
    });


    document.onkeydown = function(evt) {
        evt = evt || window.event;
        var isEscape = false;
        if ("key" in evt) {
            isEscape = (evt.key === "Escape" || evt.key === "Esc");
        } else {
            isEscape = (evt.keyCode === 27);
        }
        if (isEscape) {

            if(modals.length>0){
                //get last modal id by using pop(). 
                //This function also removes last item in array.
                var id = modals.pop();
                if($('#'+id).is(':visible')){ // if modal is not closed by click or close button
                    $('#'+id).modal('toggle');
                }
            }else{
                alert("Could not find any modals!");
            }
        }
    };

});
Continue reading "Close a Modal using the ESC Key? / Cerrar Modal usando ESC"

Determine Click Position (Row and Column Number) on click of a table cell

JQuery

 

 

Prepare a dummy HTML table for testing purpose. 'result' Div will show the corresponding row and column number when a particular cell of 'myTable' table is clicked.

<div id="result"> </div>
<table id="myTable" border="1" style="border-collapse: collapse;" cellpadding="8">
    <!--1st ROW-->
    <tr>
        <td>row 1, col 1</td>
        <td>row 1, col 2</td>
        <td>row 1, col 3</td>
        <td>row 1, col 4</td>
        <td>row 1, col 5</td>
    </tr>

    <!--2nd ROW-->
    <tr>
        <td>row 2, col 1</td>
        <td>row 2, col 2</td>
        <td>row 2, col 3</td>
        <td>row 2, col 4</td>
        <td>row 2, col 5</td>
    </tr>

    <!--3rd ROW-->
    <tr>
        <td>row 3, col 1</td>
        <td>row 3, col 2</td>
        <td>row 3, col 3</td>
        <td>row 3, col 4</td>
        <td>row 3, col 5</td>
    </tr>

    <!--4th ROW-->
    <tr>
        <td>row 4, col 1</td>
        <td>row 4, col 2</td>
        <td>row 4, col 3</td>
        <td>row 4, col 4</td>
        <td>row 4, col 5</td>
    </tr>

    <!--5th ROW-->
    <tr>
        <td>row 5, col 1</td>
        <td>row 5, col 2</td>
        <td>row 5, col 3</td>
        <td>row 5, col 4</td>
        <td>row 5, col 5</td>
    </tr>
</table>
Copy

Add following Javascript code to determine the click position on click of a table cell.

$(document).ready(function(){
    $("#myTable td").click(function() {

        var column_num = parseInt( $(this).index() ) + 1;
        var row_num = parseInt( $(this).parent().index() )+1;

        $("#result").html( "Row_num =" + row_num + "  ,  Rolumn_num ="+ column_num );
    });
});
Copy

Download SrcCodes

demo.html

Continue reading "Determine Click Position (Row and Column Number) on click of a table cell"

Ajax function return value, retormnando valor usando Ajax

Ajax success value to parent function

Just added  below lint and it worked. Is it good using the below line to fix the issue? any suggestions please

async: false,
function GetString(key) {
var keyValue = "";
$.ajax({
async: false,
type: "POST",
url: "ajax.aspx/GetCMString",
data: '{key: "' + key + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
keyValue = response.d;
},
failure: function (response) {
alert(response.d);
}
});
return keyValue;
}

<script type = "text/javascript">
function Getdata(key)
{
var data = GetString(key);
alert(data);
}
</script>

 
Continue reading "Ajax function return value, retormnando valor usando Ajax"

Alertify, cambios estilos (css)

JQuery

 

 

Either update the theme you are using or override the message CSS rules, the default theme uses the following rules:

.alertify-notifier .ajs-message {
  background: rgba(255, 255, 255, 0.95);
  color: #000;
  text-align: center;
  border: solid 1px #ddd;
  border-radius: 2px;
}
.alertify-notifier .ajs-message.ajs-success {
  color: #fff;
  background: rgba(91, 189, 114, 0.95);
  text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.5);
}
.alertify-notifier .ajs-message.ajs-error {
  color: #fff;
  background: rgba(217, 92, 92, 0.95);
  text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.5);
}
.alertify-notifier .ajs-message.ajs-warning {
  background: rgba(252, 248, 215, 0.95);
  border-color: #999;
}

To change the font color of a specific message type, override it's corresponding rule:

.alertify-notifier .ajs-message.ajs-success{
      color: blue;
}
 
Continue reading "Alertify, cambios estilos (css)"

Fetch, recuperar datos del servidor

JavaScript

 

 

Podría ocurrir que necesites enviar datos por POST pero que no dispongas de un formulario en la página donde el usuario haya escrito esos datos. Es decir, generar desde cero los datos del formulario, con variables o datos que tengas en Javascript.

Esto es perfectamente posible, aunque es algo más relativo al uso del objeto FormData que a la propia llamada Ajax con Fetch. Lo conseguimos mediante dos pasos.

  1. Creamos un objeto FormData vacío, simplemente enviando al constructor FormData los paréntesis vacíos.
  2. Creamos todos los datos arbitrarios con el método append() que recibe el dato que se quiere agregar al FormData, con su par clave/valor.

El código te quedará como puedes ver a continuación.

const data = new FormData();
data.append('empresa', 'DesarrolloWeb.com');
data.append('CIF', 'ESB00001111');
data.append('formacion_profesional', 'EscuelaIT');
fetch('../post.php', {
   method: 'POST',
   body: data
})
.then(function(response) {
   if(response.ok) {
       return response.text()
   } else {
       throw "Error en la llamada Ajax";
   }

})
.then(function(texto) {
   console.log(texto);
})
.catch(function(err) {
   console.log(err);
});

 

Continue reading "Fetch, recuperar datos del servidor"

Insertar Html dentro de otro HTML

JavaScriptJQuery

 

 

My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:

a.html:

<html> 
  <body>
  <h1>Put your HTML content before insertion of b.js.</h1>
      ...

  <script src="b.js"></script>

      ...

  <p>And whatever content you want afterwards.</p>
  </body>
</html>

Alternatively for browsers that support template literals the following also works:

b.js:

document.write(`

    <h1>Add your HTML code here</h1>

     <p>Notice, you do not have to escape LF's with a '\',
        like demonstrated in the above code listing.
    </p>

`);
 
Continue reading "Insertar Html dentro de otro HTML"

Tabulator, table, multiple filtro

JQuery


FILTROS CON SELECTORES CHOSEN, ACUMULAR FILTROS USANDO TABULATOR

selGrupos.on('change',function (){
    var filters = table.getFilters();
    $.each(filters, function (i,row) {
        if (row.field==="artgru") {
            table.removeFilter(row.field,row.type,row.value)
        }
    })
    if ($(this).val()!=='0') {
        table.addFilter("artgru", "like", $(this).val());
    }
});

selLineas.on('change',function (){
    var filters = table.getFilters();
    $.each(filters, function (i,row) {
        if (row.field==="artlin") {
            table.removeFilter(row.field,row.type,row.value)
        }
    })
    if ($(this).val()!=='0') {
        table.addFilter("artlin", "like", $(this).val());
    }
});