Questions and answers using Ajax

Asked

Viewed 55 times

-1

I’m making a <form> that returns an interaction if the answer is wrong.

The idea is: if the user selects the right answer, the <button> change the color to green and/or red for wrong. This using $.ajax dynamically without the page being updated!

Would anyone have any idea how to catch the value selected in radio button and compare with the correct answer, within this code? Or would have a better way?

<form name="frm.$row[question_id]." role="form" id="submitForm.$row[question_id].">
    <input type="hidden" class="form-control" name="question_id" placeholder="Name" value=".$row[question_id]." required="" />
    <input type="hidden" class="form-control" name="user_id" placeholder="User" value=".$myid." required="" />
    <div class="form-check">
        <input class="form-check-input.$row[question_id]." type="radio" name="resposta" id="blankRadio1" value="A" aria-label="..." onClick="mostrar.$row[question_id].()" />
        A) .$row[option1].
    </div>
    <div class="form-check">
        <input class="form-check-input.$row[question_id]." type="radio" name="resposta" id="blankRadio1" value="B" aria-label="..." onClick="mostrar.$row[question_id].()" />
        B) .$row[option2].
    </div>
    <div class="form-check">
        <input class="form-check-input.$row[question_id]." type="radio" name="resposta" id="blankRadio1" value="C" aria-label="..." onClick="mostrar.$row[question_id].()" />
        C) .$row[option3].
    </div>
    <div class="form-check">
        <input class="form-check-input.$row[question_id]." type="radio" name="resposta" id="blankRadio1" value="D" aria-label="..." onClick="mostrar.$row[question_id].()" />
        D) .$row[option4].
    </div>
    <br />
    <button type="submit" class="btn btn-info btn btn-block" id="submitbtn.$row[question_id]." name="botao.$row[question_id]." disabled>Responder</button>
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $("#submitForm.$row[question_id].").on("submit", function (e) {
            e.preventDefault();
            $("#submitbtn").text("Please wait..");
            var userForm = $(this).serialize();
            $.ajax({
                url: "insertData.php",
                type: "POST",
                cache: false,
                data: userForm,
                success: function (response) {
                    $("#submitbtn.$row[question_id].").attr("disabled", true);
                    $("#success").show();
                    $("#success").html("Data inserted successfully");
                    $("#submitbtn.$row[question_id].").text("Gabarito: .$row[answer].");
                    $("#submitForm")[0].reset();
                },
            });
        });
    });
</script>

1 answer

0


First of all..

information was missing in your question, so I suggest that DON’T LET to see How to create a Minimum, Complete and Verifiable example and How to ask a good question? to thus elaborate a question without leaving any detail behind.. In this case, your code has been missing to complement but without problems!


I rode a "skimming" of simple questions/answers using jQuery

$(function() {
    $.ajax({
        url: `questoes.php?obter-questoes`,
        type: "get",
        dataType: "json",
        cache: false,
        success: (json, status, xhr) => {
        console.log(json);
            $("#frmMain h3").html(Object.keys(json)[0]);
            Object.values(json)[0].forEach((value, index) => {
                $("#frmMain ul").append(`<li><input type="radio" name="respostas" value="${index}" />${value}</li>`);
            });
        }
    });
});

$("#frmMain").on("submit", function(e) {
    e.preventDefault();
    $.ajax({
        url: `questoes.php?obter-respostas`,
        type: "post",
        dataType: "json",
        cache: false,
        data: {
            "questao": $("#frmMain h3").html(),
            "resposta": $("[type=radio][name=respostas]:checked").val()
        },
        success: (json, status, xhr) => {
            Object.entries(json).forEach((value, index) => {
                if ((value[1] == true)) {
                    $("[type=radio][name=respostas]").each(function() {
                        if ((value[0] == $(this).parent().text())) {
                            $(this).parent().css("background-color", "lime");
                        } else {
                            $(this).parent().css("background-color", "red");
                        }
                    });
                }
            });
        }
    })

});
form { max-width: 30%; }
li { list-style-type: none; }
ul { padding-inline-start: 0px !important; }
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Perguntas e Respostas</title>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
    <form id="frmMain">
        <h3></h3>
        <ul></ul>
        <button type="submit">Responder</button>
    </form>
</body>
</html>

Already in the back-end is a very small code..

However you could do using only Javascript

  • questoes.php
<?php  
    
    // Com apenas 4 questões, mas poderá utilizar alguma API para obter questões (tipo: Quiz)
    $questoes = array(
        "Quem é o atual presidente do Brasil?" => array(
            "Lula" => false,
            "Dilma Rousseff" => false,
            "Jair Bolsonaro" => true,
            "Michel Temer" => false
        ),
        "Quanto é 2 x 2 = ?" => array(
            "2" => false,
            "5" => false,
            "8" => false,
            "4" => true
        ),
        "O que significa Legend em Português?" => array(
            "Legenda" => true,
            "História" => false,
            "Conto" => false,
            "Legado" => false
        ),
        "Qual melhor site de perguntas e respostas?" => array(
            "Reddit" => false,
            "Stack Overflow em Português" => true,
            "Quora" => false,
            "Comunidades da Microsoft" => false
        )
    );


    if (isset($_GET["obter-questoes"])) {
        // randomiza os indices das chaves saindo de forma "aleatória"..
        $questao = array_keys($questoes)[rand(0, count($questoes) - 1)];

        // adiciona a um novo array contendo apenas as chaves pais/filhos sem a resposta true/false
        $retorno[$questao] = array_keys($questoes[$questao]);

        // imprime o resultado (será o response da solicitação ajax)
        print_r(json_encode($retorno));

    } else if (isset($_GET["obter-respostas"])) {
        
        // uma simples busca baseado no nome da questão e a resposta selecionada..
        print_r(json_encode($questoes[$_POST["questao"]]));
    }   

?>

Test the code!

  • Vlw, gleisin-dev. Thanks! I got dps right away by comparing the userFrom variable with the selected value on the radio. It was not working because it is more of a value that this variable takes. I fixed it and it worked. if(userForm == "answer='. $Row['Answer']. '&question_id='. $Row['question_id']. '&user_id='. $myid. '") { $("#submitbtn'. $Row['question_id']. '"). removeClass("btn-Danger"). addClass("btn-Success"); } Else{$("#submitbtn'. $Row['question_id']. '"). removeClass("btn-Success"). addClass("btn-Danger");}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.