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?