0

estoy haciendo un sistema de quiz, estoy recibiendo datos desde mi base de datos y no tengo ningún problema con esto, estoy recibiendo los datos desde esta tabla

    {
        Schema::create('preguntas', function (Blueprint $table) {
            $table->id('id_preguntas');
            $table->unsignedBigInteger('fk_categoria');
            $table->unsignedBigInteger('fk_usuario');
            $table->string('pregunta');
            $table->string('respuesta_correcta');
            $table->string('respuesta_2');
            $table->string('respuesta_3');
            $table->string('respuesta_4');
            $table->string('retroalimentacion_positiva');
            $table->string('retroalimentacion_negativa');
            $table->integer('dificultad');
            $table->foreign('fk_categoria')->references('id_categoria_preguntas')->on('categoria_preguntas');
            $table->foreign('fk_usuario')->references('id')->on('users');
            $table->integer('estado')->default(0);
            $table->timestamps();
        });
    }```

Lo estoy recibiendo en mi javascript en el que cuento con una libreria de uso libre de JC Hamill en la cual construye el html de las preguntas que seria este

!function (a, b, c, d) { "use strict"; a.quiz = function (b, d) { var e = this; e.$el = a(b), e.$el.data("quiz", e), e.options = a.extend(a.quiz.defaultOptions, d); var f = e.options.questions, g = f.length, h = e.options.startScreen, i = e.options.startButton, j = e.options.homeButton, k = e.options.resultsScreen, l = e.options.gameOverScreen, m = 1, n = 0, o = !1; e.methods = { init: function () { e.methods.setup(), a(c).on("click", i, function (a) { a.preventDefault(), e.methods.start() }), a(c).on("click", j, function (a) { a.preventDefault(), e.methods.home() }), a(c).on("click", ".answers a", function (a) { a.preventDefault(), e.methods.answerQuestion(this) }), a(c).on("click", "#quiz-next-btn", function (a) { a.preventDefault(), e.methods.nextQuestion() }), a(c).on("click", "#quiz-finish-btn", function (a) { a.preventDefault(), e.methods.finish() }), a(c).on("click", "#quiz-restart-btn, #quiz-retry-btn", function (a) { a.preventDefault(), e.methods.restart() }) }, setup: function () { var b = ""; e.options.counter && (b += '<div id="quiz-counter"></div>'), b += '<div id="questions">', a.each(f, function (c, d) { b += '<div class="question-container">', b += '<p class="question">' + d.q + "</p>", b += '<ul class="answers">', a.each(d.options, function (a, c) { b += '<li><a href="#" data-index="' + a + '">' + c + "</a></li>" }), b += "</ul>", b += "</div>" }), b += "</div>", 0 === a(k).length && (b += '<div id="' + k.substr(1) + '">', b += '<p id="quiz-results"></p>', b += "</div>"), b += '<div id="quiz-controls">', b += '<p id="quiz-response"></p>', b += '<div id="quiz-buttons">', b += '<a href="#" id="quiz-next-btn">Siguiente</a>', b += '<a href="#" id="quiz-finish-btn">Finalizar</a>', b += '<a href="#" id="quiz-restart-btn">Reiniciar</a>', b += "</div>", b += "</div>", e.$el.append(b).addClass("quiz-container quiz-start-state"), a("#quiz-counter").hide(), a(".question-container").hide(), a(l).hide(), a(k).hide(), a("#quiz-controls").hide() }, start: function () { e.$el.removeClass("quiz-start-state").addClass("quiz-questions-state"), a(h).hide(), a("#quiz-controls").hide(), a("#quiz-finish-btn").hide(), a("#quiz-restart-btn").hide(), a("#questions").show(), a("#quiz-counter").show(), a(".question-container:first-child").show().addClass("active-question"), e.methods.updateCounter() }, answerQuestion: function (b) { if (!o) { o = !0; var c = a(b), d = "", g = c.data("index"), h = m - 1, i = f[h].correctIndex; if (g === i) c.addClass("correct"), d = f[h].correctResponse, n++; else if (c.addClass("incorrect"), d = f[h].incorrectResponse, !e.options.allowIncorrect) return void e.methods.gameOver(d); a("#quiz-response").html(d), a("#quiz-controls").fadeIn(), "function" == typeof e.options.answerCallback && e.options.answerCallback(m, g === i) } }, nextQuestion: function () { o = !1, a(".active-question").hide().removeClass("active-question").next(".question-container").show().addClass("active-question"), a("#quiz-controls").hide(), ++m === g && (a("#quiz-next-btn").hide(), a("#quiz-finish-btn").show()), e.methods.updateCounter(), "function" == typeof e.options.nextCallback && e.options.nextCallback() }, gameOver: function (b) { if (0 === a(l).length) { var c = ""; c += '<div id="' + l.substr(1) + '">', c += '<p id="quiz-gameover-response"></p>', c += '<p><a href="#" id="quiz-retry-btn">Retry</a></p>', c += "</div>", e.$el.append(c) } a("#quiz-gameover-response").html(b), a("#quiz-counter").hide(), a("#questions").hide(), a(l).show() }, finish: function () { e.$el.removeClass("quiz-questions-state").addClass("quiz-results-state"), a(".active-question").hide().removeClass("active-question"), a("#quiz-counter").hide(), a("#quiz-response").hide(), a("#quiz-finish-btn").hide(), a("#quiz-next-btn").hide(), a("#quiz-restart-btn").show(), a(k).show(), a("#quiz-results").html("¡Conseguiste " + n + " de " + g + " respuestas correctas!"), "function" == typeof e.options.finishCallback && e.options.finishCallback() }, restart: function () { e.methods.reset(), e.$el.addClass("quiz-questions-state"), a("#questions").show(), a("#quiz-counter").show(), a(".question-container:first-child").show().addClass("active-question"), e.methods.updateCounter() }, reset: function () { o = !1, m = 1, n = 0, a(".answers a").removeClass("correct incorrect"), e.$el.removeClass().addClass("quiz-container"), a("#quiz-restart-btn").hide(), a(l).hide(), a(k).hide(), a("#quiz-controls").hide(), a("#quiz-response").show(), a("#quiz-next-btn").show(), a("#quiz-counter").hide(), a(".active-question").hide().removeClass("active-question") }, home: function () { e.methods.reset(), e.$el.addClass("quiz-start-state"), a(h).show(), "function" == typeof e.options.homeCallback && e.options.homeCallback() }, updateCounter: function () { var b = e.options.counterFormat.replace("%current", m).replace("%total", g); a("#quiz-counter").html(b) } }, e.methods.init() }, a.quiz.defaultOptions = { allowIncorrect: !0, counter: !0, counterFormat: "%current/%total", startScreen: "#quiz-start-screen", startButton: "#quiz-start-btn", homeButton: "#quiz-home-btn", resultsScreen: "#quiz-results-screen", gameOverScreen: "#quiz-gameover-screen" }, a.fn.quiz = function (b) { return this.each(function () { new a.quiz(this, b) }) } }(jQuery, window, document);

Entonces aqui es donde se entregan las preguntas para que pueda ser construido que se las estoy entregando a través del metodo public function obtener_preguntas (codigo de consulta sql) Y luego tengo donde estoy recibiendo todos los datos que seria en mi javascript y un trozo del codigo donde va el html, solo se llama a el javascript donde se construye el html para funcionar




    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    function cargarPreguntas() {
        $.ajax({
            url: '/obtener_preguntas', // Ruta que devuelve preguntas y respuestas desde el servidor
            method: 'GET',
            success: function (data) {
                var preguntas = [];
                data.forEach(function (item) {
                    // Crear un arreglo con todas las opciones de respuesta
                    var opcionesRespuesta = [item.respuesta_correcta, item.respuesta_2, item.respuesta_3, item.respuesta_4];
                    // Mezclar las opciones de respuesta
                    shuffleArray(opcionesRespuesta);
                    // Encontrar el índice de la respuesta correcta en el arreglo mezclado
                    var correctIndex = opcionesRespuesta.indexOf(item.respuesta_correcta);

                    var pregunta = {
                        'q': item.pregunta, // Pregunta
                        'options': opcionesRespuesta, // Opciones mezcladas
                        'correctIndex': correctIndex, // Índice de la respuesta correcta
                        'correctResponse': item.retroalimentacion_positiva, // Retroalimentación positiva
                        'incorrectResponse': item.retroalimentacion_negativa // Retroalimentación negativa
                    };
                    preguntas.push(pregunta);
                });

                // Inicializa el plugin 'quiz' con las preguntas cargadas
                $('#quiz').quiz({
                    counterFormat: 'Pregunta %current de %total',
                    questions: preguntas
                    // Otras opciones del plugin 'quiz'...
                });
            },
            error: function (error) {
                console.error('Error al cargar las preguntas: ' + error);
            }
        });
    }

    // Llama a la función para cargar preguntas cuando la página se carga
    $(document).ready(function () {
      cargarPreguntas();
    });

<!-- language: lang-html -->

    <main>
            <div class="container">
                <div id="quiz">
                    <div id="quiz-header">
                        <h1>Quiz Variado</h1>
                    </div>
                    <div id="quiz-start-screen">
                        <p><a href="#" id="quiz-start-btn" class="quiz-button">Comenzar</a></p>
                    </div>
                </div>
            </div>
        </main>

Mi problema es que he intentado varias formas de mandar las respuestas a mi base de datos pero no he podido y estoy muy frustrado ya que he intentado con ajax bastante pero no me a resultado y no logro entender porque intente dando la etiqueta csrf para no tener problemas tambien

    // Configura las cabeceras con el token CSRF
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    function cargarPreguntas() {
      $.ajax({
          url: '/obtener_preguntas',
          method: 'GET',
          success: function (data) {
              var preguntas = [];
              data.forEach(function (item) {
                  var opcionesRespuesta = [item.respuesta_correcta, item.respuesta_2, item.respuesta_3, item.respuesta_4];
                  shuffleArray(opcionesRespuesta);
                  var correctIndex = opcionesRespuesta.indexOf(item.respuesta_correcta);

                  var pregunta = {
                      'q': item.pregunta,
                      'options': opcionesRespuesta,
                      'correctIndex': correctIndex,
                      'correctResponse': item.retroalimentacion_positiva,
                      'incorrectResponse': item.retroalimentacion_negativa
                  };
                  preguntas.push(pregunta);
              });

              // Inicializa el plugin 'quiz' con las preguntas cargadas
              $('#quiz').quiz({
                  counterFormat: 'Pregunta %current de %total',
                  questions: preguntas,
                  callback: function (index, item) {
                      // Cuando se responde a una pregunta, obtén la respuesta seleccionada por el usuario
                      var selectedOption = $('input[name="question' + index + '"]:checked').val();
                      
                      // Agrega console.log para depurar
                      console.log('Respuesta seleccionada:', selectedOption);
                      console.log('Respuesta correcta:', item.options[item.correctIndex]);

                      // Envia la respuesta seleccionada y la respuesta correcta al servidor
                      $.ajax({
                          url: '/registrar_respuesta',
                          method: 'POST',
                          data: {
                              selectedOption: selectedOption,
                              correctOption: item.options[item.correctIndex]
                          },
                          success: function (response) {
                              console.log(response);
                          },
                          error: function (error) {
                              console.error('Error al registrar la respuesta: ' + error);
                          }
                      });
                  }
              });
          },
          error: function (error) {
              console.error('Error al cargar las preguntas: ' + error);
          }
      });
    }

    // Llama a la función para cargar preguntas cuando la página se carga
    $(document).ready(function () {
      cargarPreguntas();
    });


pero esto no funciona, espero que se entienda mi inquietud y de antemano muchas gracias, subo el proyecto por si no se entiende el codigo APP

A modo de resumen el problema que tengo es que al momento de querer enviar datos a mysql desde javascript estoy teniendo problemas, incluso intentándolo con ajax en este punto no puedo encontrar que hacer

ACTUALIZACION

He logrado mandar datos a la base de datos pero no he encontrado como obtener el id de la pregunta y la respuesta seleccionada ya que todo se construye al momento de iniciar el formulario

function manejarRespuesta(preguntaId, respuesta) {
  // Supongamos que tienes el ID de la pregunta y la respuesta seleccionada

  // Crear un objeto con los datos que deseas enviar al servidor
  var datos = {
      preguntaId: preguntaId,
      respuesta: respuesta
  };

  // Realizar una solicitud AJAX al servidor para guardar la respuesta
  $.ajax({
      url: '/registrar_respuesta', // Ruta en el servidor para guardar la respuesta
      method: 'get',
      data: datos,
      success: function (respuesta) {
          // Manejar la respuesta del servidor (puede ser un mensaje de confirmación, etc.)
      },
      error: function (error) {
          console.error('Error al guardar la respuesta: ' + error);
      }
  });
}

0

Examina otras preguntas con la etiqueta o formula tu propia pregunta.