0

I'm trying to manage data from a php function in JSON, but when I try to Access it, my Ajax always goes to error method.

My PHP Function:

function retornarPreguntas()
{
    try {
        global $conexion;
        $query = $conexion->query('SELECT idPreguntas, Pregunta, Categoria, Visible, formato FROM preguntas');
        $query->execute();
        $preguntas = $query->fetchAll(PDO::FETCH_ASSOC);
        header('Content-type:application/json;charset=utf-8');  
        $json = json_encode($preguntas);
        echo $json;
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }   
}

my JQuery Function

            function crearPreguntas() {
              $.ajax({
                url: "includes/RespuestasAjax.php",
                type: "POST",
                data: {
                  funcion: "retornarPreguntas"
                },
                dataType: "json",
                success: function(data) {
                  var html = "<tr><td colspan='5' align='center'>Evaluación</td></tr>";
                  html += '<tr><td colspan="5" align="center">Factores Generales de desempeño y rendimiento</td></tr>';
                  //var factores = retornarFactores();
                  alert("uno");
                  for (var i = 0; i < data.length; i++) {
                    html += '<tr>';
                    html += '<td>' + data[i]['pregunta'] + '</td>';
                    html += '<td><select id="pregunta' + i + '">';
                    for (k = 1; k <= 5; k++) {
                      html += '<option value="' + k + '">' + k + '</option>';
                    }
                    html += '</tr>';
                  }
                  $('#preguntas').empty();
                  $('#preguntas').append(html);
                },
                error: function(codigo) {
                  console.log(codigo);
                }
              });
            }

If I change my PHP function to print_r my alert display the data, but I can't Access by key index, if I try json then it gives me the error:

[object Object]{readyState: 4, responseText: "", status: 200, statusText: "OK"}

Any idea of what I'm doing wrong?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
GlacialVoid
  • 145
  • 1
  • 1
  • 7
  • 2
    The Ajax request with `dataType: json` throws an error when Your reponse cannot be parsed as `JSON` so please check if you are able to `json_encode` the data correctly and check your query. – maniteja Sep 09 '15 at 15:54
  • Check the network tab of the console, if you have error reporting enabled in your php script, and a notice or warning is being generated, that will be echoed out before the json and invalidate it causing this error. I bet you have something like `Notice: Undefined variable: ....` – Wesley Smith Sep 09 '15 at 15:55
  • 1
    jQuery's `error` callback has more info than what you are showing. Change the `error` callback to `error: function(jqXHR, status, error){ console.log(status, error); }`. – gen_Eric Sep 09 '15 at 15:56
  • "SyntaxError: Error de sintaxis at m.parseJSON (http://localhost/RRHH/assets/js/jquery.min.js:5:15984) at Pb (http://localhost/RRHH/assets/js/jquery.min.js:5:18377) at x (http://localhost/RRHH/assets/js/jquery.min.js:5:21791) at b (http://localhost/RRHH/assets/js/jquery.min.js:5:26030)" – GlacialVoid Sep 09 '15 at 16:00
  • I notice that you are setting `data: { funcion: "retornarPreguntas" }` in your ajax (note the misspelling of `function`) If your php file does something like `$function = $_POST['data']['function'];` that would cause this error because `$function` would be undefined, you would need to fix the misspelling and should instead write that more like `$data= isset($_POST['data']['function']) ? $_POST['data']['function'] : null;` to avoid the warning if the value doesn't exist – Wesley Smith Sep 09 '15 at 16:03
  • @GlacialVoid: Either you're getting a `PDOException`, so it's printing the `"Error:"` or you're printing something else before/after the JSON data. Or, maybe your query is returning 0 rows. – gen_Eric Sep 09 '15 at 16:04
  • @DelightedD0D funcion is the spanish of function, I'm using that as post to use it in a switch(funcion) { case 'retornarPreguntas' : retornarPreguntas(); break; } I think I know why the json has error, my Query has a text field with questions that contains comma, maybe that's the problem. – GlacialVoid Sep 09 '15 at 16:08
  • Fair enough, I'm pretty sure json_encode takes care of the comas though. Did you look at the network tab in the console? if there is an error, outside the json itself, it will be very evident – Wesley Smith Sep 09 '15 at 16:11
  • @DelightedD0D after all this, I excluded the "pregunta" column from my query and error is gone, maybe there's a special character or something that json_encode doesn't like. My field has: utf8_general_ci and DB: utf8mb4_general_ci. For example: "Aplica los conceptos, técnicas y procedimientos que conoce, en la realización de su trabajo." this breaks the json_encode because acute accent, some even have ñ. – GlacialVoid Sep 09 '15 at 16:15
  • 1
    Try putting `echo json_last_error();` right after your `json_encode`. What message does that give? – Wesley Smith Sep 09 '15 at 16:18
  • @DelightedD0D error code 5 – GlacialVoid Sep 09 '15 at 16:22
  • 1
    Ok, that means "5 = JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded" The issue is likely the accents used in the spanish questions. [See this question](http://stackoverflow.com/questions/2790027/utf-8-character-encoding-battles-json-encode) – Wesley Smith Sep 09 '15 at 16:28

1 Answers1

0

I just added this to my php code:

$preguntas = $query->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: text/html;charset=utf-8');
$json = json_encode($preguntas);

Instead of:

$preguntas = $query->fetchAll(PDO::FETCH_ASSOC);
**header('Content-type:application/json;charset=utf-8');**  
$json = json_encode($preguntas);
GlacialVoid
  • 145
  • 1
  • 1
  • 7