send all values by ajax

1

What I try to do is send the response of a request but I do not receive the values of the array I only receive the word array

// js file where I get the answer

$(document).ready(function(){
//alert("hola");
let selectCards =$('#cards');  
let selectEstados =  $('#estados');
let columna = 'commerce_brand';
//let selectCards = document.querySelector('#cards');

function cargarOpciones (idSelectIndependiente, columna, idSelectDependiente){
console.log(idSelectIndependiente);
console.log("entrando");

 $.ajax({
        type:'POST',
        url: 'cargar_estados.php',
        data:{
                'peticion': 'idSelectIndependiente',
                'num':columna
            }
        //dataType:'json'
    })

    .done(function(lista_rep1){
        
        console.log(lista_rep1);




         // idSelectIndependiente.empty();
         // idSelectIndependiente.append('<option value="">Elige una opcion</option>');
         // idSelectIndependiente.html('<option value="lista_rep1[i][commerce_brand]">lista_rep1[commerce_brand]</option>');
         for (var i = 0; i < lista_rep1.length; i++) {
            
            //myObj.cars[i];
        // idSelectIndependiente.append("<option value='lista_rep1[i][commerce_brand]'>lista_rep1[i][commerce_brand]</option>");
       // idSelectIndependiente.append('<option value="'+lista_rep1[i]['commerce_brand']+'">'+lista_rep1[i][1]+'</option>');
    
        console.log(lista_rep1);
        };
    })
    .fail(function(){
        alert('error al cargar las listas');
    });
console.log("saliendo");
}

cargarOpciones(selectCards, columna)

// archivo php donde recibo los datos de la petición ajax y envio una respuesta.
<?php
require_once 'conexion.php';

$cards = $_POST['peticion'];
$columna = $_POST['num'];
//echo $columna;




function getData($idSelect = false, $columna){
    
    switch ($columna){
        case 'commerce_brand':
            $con = getCon();
            $query = "SELECT commerce_brand FROM 'commerc' group by commerce_brand";
            $result = $con->query($query);
            $row = $result->fetch_array();

            //$listas = json_encode($row);
            /// while($row = $result->fetch_array(MYSQLI_ASSOC)){
               // $listas.=" ";
               // $listas  .= $row[commerce_brand];
                //}

            //
            return $row;
        break;
        
        default:
            $probando = "viene por defecto";
        return $probando;
    }
}

echo getData($cards,$columna);
    
asked by javier 30.10.2018 в 16:34
source

1 answer

0

There are several problems in your code.

I list them in their order of appearance and at the end I propose a correction:

  • You must control the variables that you receive in the POST
  • You must be consistent in the answer. If Ajax expects a JSON, you can not put a string like you do in default .
  • You can not get anything else on the screen, just the JSON. That means that any file you include, like this require_once 'conexion.php'; can not get anything out of the screen, or error messages or anything, not even a blank space. That must be very clear. A lot of people err in that way.
  • It is a good idea to put an encabazado of which the content is JSON
  • And finally return what Ajax expects, a JSON.

That said, I propose this code:

<?php
    /*Verificamos los datos posteados usando ternarios*/
    $cards =   (empty($_POST['peticion'])) ? NULL : $_POST['peticion'];
    $columna = (empty($_POST['num'])) ?      NULL : $_POST['num'];   
    //echo $columna;  Esto no lo hagas ni de broma, ningún echo de nada
    /*Si están nulos no hacemos require ni llamamos el código para hacer nada*/
    if ($cards && $columna){
        require_once 'conexion.php';  //¿Seguro que este archivo no tiene ninguna salida por pantalla?
        $json=getData($cards,$columna);
    }else{
        $json=array("error"=>"No hay datos en el POST");    
    }
    /*
        *Pase lo que pase este código devuelve un JSON
        *es lo que Ajax espera
    */
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($json);

    function getData($idSelect = false, $columna){
        switch ($columna){
            case 'commerce_brand':
                $con = getCon();
                $query = "SELECT commerce_brand FROM 'commerc' group by commerce_brand";
                $result = $con->query($query);

                /*
                   *Si la consulta trae más de una fila
                   *hay que abrir un bucle para leer cada fila
                */
                while ($datos = $resultado->fetch_row()) {
                    $row[]=$datos;
                }
                return $row;
            break;

            default:
                $probando = array ("error"=>"La columna $columna no está admitida");
                return $probando;
        }
    }
?>

Other reasons why an Ajax request with JSON fails

  • Because the data comes badly encoded from the database and that creates a wrong json sometimes
  • Because you are sending the request to the wrong file
answered by 30.10.2018 / 17:03
source