I have problems recovering an array in jQuery from Ajax

2

I have the following code in jQuery:

$("#Eng").click(function(evento){
  alert ("Entro en cambio idioma.");
  //elimino el comportamiento por defecto del enlace
  evento.preventDefault();
  $.ajax({
      type: 'GET',
      url: 'FAjax.php',
      data: {Eng},
      dataType: 'json',
            processData: false,
        contentType: 'application/json; charset=utf-8',
      cache: false,
    error: function(jqXHR, textStatus, errorThrown){
          alert("error ==>" + jqXHR.statusText);
          alert("excepcion ==>" + errorThrown);
    },
      success: function(result) {
              console.log(data);
                /*
            $('#tit').html(result[25]);
            $('#LCantAves').html(result[23]);
          $('#LActual').html(result[0]);
            $('#sub').html(result[3]);
            $('#idiom').html(result[10]);
            $('#Com').html(result[15]);
            $('#Ord').html(result[16]);
            $('#Cie').html(result[14]);
            $('#Ref').html(result[22]);
            $('#Rec').html(result[21]);
            $('#Enl').html(result[12]);
                */
      }
    });
});

and this is the php code:

<?php
function cambioIdioma($lang) {
  $_SESSION[Idioma] = $lang;

    $serverdb='localhost';
    $usuariobd='root';
    $passwddb='*******';
    $basedb='********';

    $conexion = mysqli_connect("$serverdb", "$usuariobd", "$passwddb", "$basedb");
    mysqli_set_charset($conexion, 'utf8');

    if (!$conexion) {
        die('<strong>No pudo conectarse a la bse de datos:</strong> ' . mysqli_connect_error());
    }

        /* Consulta */
        $qry = "SELECT * FROM lits WHERE Lang = '$lang';";
    $res = mysqli_query($conexion, $qry);

    $nvoitem = array();

    while($linea = mysqli_fetch_assoc($res)) {
            $nvoitem = array ($linea['Actu']| $linea['Alim']| $linea['Band']| $linea['Bienve']| $linea['Contacto']| $linea['Descrip']| $linea['Env']| $linea['Flia']| $linea['Habi']| $linea['Home']| $linea['Idioma']| $linea['Leng']| $linea['Links']| $linea['Nidif']| $linea['NomCient']| $linea['NomCom']| $linea['NomOrd']| $linea['Orden']| $linea['Otras']| $linea['Pampa']| $linea['Peso']| $linea['Rec']| $linea['Ref']| $linea['Reg']| $linea['Tam']| $linea['Tit']| $linea['Todas']| $linea['Volver']);
    }

    mysqli_free_result($res);
        mysqli_close($conexion);

    echo json_encode($nvoitem);
}
?>

The issue is not only that I do not receive anything, but I do not know what the problem is.

    
asked by mdimatteo 09.03.2017 в 21:15
source

2 answers

1

First, the variable Eng is not declared. It sounds like if you click the #Eng element, you take it for granted that the language is English.

If that is the case, then it should look something like this:

$("#Eng").click(function(evento){
  alert ("Entro en cambio idioma.");
  //elimino el comportamiento por defecto del enlace
  evento.preventDefault();
  $.ajax({
      type: 'GET',
      url: 'FAjax.php',
      data: {lang : 'Eng'},
      ...
  });
});

On the server side it does not appear how you call the function to change language, so we should assume that it is something like:

<?php 

function cambioIdioma($lang) {

}
$lenguaje = $_GET['lang'];
cambioIdioma($lenguaje);

And if that is the case, then there is a problem getting the rows of the table. Because where it says:

while($linea = mysqli_fetch_assoc($res)) {
            $nvoitem = array ($linea['Actu']| $linea['Alim']| $linea['Band']| $linea['Bienve']| $linea['Contacto']| $linea['Descrip']| $linea['Env']| $linea['Flia']| $linea['Habi']| $linea['Home']| $linea['Idioma']| $linea['Leng']| $linea['Links']| $linea['Nidif']| $linea['NomCient']| $linea['NomCom']| $linea['NomOrd']| $linea['Orden']| $linea['Otras']| $linea['Pampa']| $linea['Peso']| $linea['Rec']| $linea['Ref']| $linea['Reg']| $linea['Tam']| $linea['Tit']| $linea['Todas']| $linea['Volver']);
}

The separator should be a comma and not a pipe | , leaving

while($linea = mysqli_fetch_assoc($res)) {
                $nvoitem = array ($linea['Actu'], $linea['Alim'], $linea['Band'], $linea['Bienve'], $linea['Contacto'], $linea['Descrip'], $linea['Env'], $linea['Flia'], $linea['Habi'], $linea['Home'], $linea['Idioma'], $linea['Leng'], $linea['Links'], $linea['Nidif'], $linea['NomCient'], $linea['NomCom'], $linea['NomOrd'], $linea['Orden'], $linea['Otras'], $linea['Pampa'], $linea['Peso'], $linea['Rec'], $linea['Ref'], $linea['Reg'], $linea['Tam'], $linea['Tit'], $linea['Todas'], $linea['Volver']);
}
    
answered by 09.03.2017 в 23:25
0

Errors

1.- When trying to send by ajax the language Eng to the file FAjax.php , you are doing it wrong ( eg: data: {Eng} )

2.- When trying to generate an array ( $nvoitem ) with the language data, instead of creating an array with data, you are creating an array with a boolean.

Solutions

1.- Send via ajax by GET to the file FAjax.php the variable lang with the value Eng .

$("#Eng").click(function(evento){
  alert ("Entro en cambio idioma.");
  //elimino el comportamiento por defecto del enlace
  evento.preventDefault();
  $.ajax({
    type: 'GET',
    url: 'FAjax.php',
    data: {lang: 'Eng'}, // <-- Aquí el cambio
    dataType: 'json',
    processData: false,
    contentType: 'application/json; charset=utf-8',
    cache: false,
    error: function(jqXHR, textStatus, errorThrown){
      alert("error ==>" + jqXHR.statusText);
      alert("excepcion ==>" + errorThrown);
    },
    success: function(result) {
      console.log(result);

      // Modifique el arreglo por una matriz asociativa para
      // que sea mas legible saber que dato se está enviando
      $('#tit').html(result.Tit);
      $('#LCantAves').html(result.Reg);
      $('#LActual').html(result.Actu);
      $('#sub').html(result.Bienve);
      $('#idiom').html(result.Idioma);
      $('#Com').html(result.NomCom);
      $('#Ord').html(result.NomOrd);
      $('#Cie').html(result.NomClient);
      $('#Ref').html(result.Ref);
      $('#Rec').html(result.Rec);
      $('#Enl').html(result.Links);
    }
  });
});

2.- To make the data collection more readable, it seems to me that it is better to return an associative matrix, instead of an arrangement of positions.

<?php
function cambioIdioma($lang) {
    $_SESSION[Idioma] = $lang;

    $serverdb='localhost';
    $usuariobd='root';
    $passwddb='*******';
    $basedb='********';

    $conexion = mysqli_connect($serverdb, $usuariobd, $passwddb, $basedb); // <-- AQUI pasamos la variables directamente
    mysqli_set_charset($conexion, 'utf8');

    if (!$conexion) {
        die('<strong>No pudo conectarse a la bse de datos:</strong> ' . mysqli_connect_error());
    }

    /* Consulta */
    $qry = "SELECT * FROM lits WHERE Lang = '$lang'";// <-- AQUI El ';' dentro del string esta de mas.
    $res = mysqli_query($conexion, $qry);

    $nvoitem = mysqli_fetch_assoc($res); // <-- AQUI Se supone que hay un solo idioma, por lo que no debería hacer falta iterar

    mysqli_free_result($res);
    mysqli_close($conexion);

    echo json_encode($nvoitem);
}
?>

Note: To pass the language to the cambioIdioma function, inside the FAjax.php file, you should do so:

cambioIdioma($_GET['lang']);
    
answered by 09.03.2017 в 23:30