Combine alternative array with query array php/jquery

Asked

Viewed 127 times

0

My doubt is the following: I have this code jquery where I capture all the questions of a proof and just below the alternatives of it; but I can’t relate the alternatives to the questions, someone can help me, I’ve tried everything I think.

follows html

<form action="" method="post">
<li><textarea name="quest[]" placeholder="Digite seu texto aqui." required=""></textarea>
<input type="text" id="quest1" name="alternativa[]" value="a)" required="">
<input type="text" id="quest1" name="alternativa[]" value="b)" required=""></li>

<li><textarea name="quest[]" placeholder="Digite seu texto aqui." required=""></textarea>
<input type="text" id="quest2" name="alternativa[]" value="a)" required="">
<input type="text" id="quest2" name="alternativa[]" value="b)" required="">
<input type="text" id="quest2" name="alternativa[]" value="c)" required=""></li></form>

$("body").on('click', 'button[name="enviaProva"]', function (e) {
    e.preventDefault();
    var textarea = [];        
    var input = [];


    $('textarea[name="quest[]"]').each(function () {
        textarea.push($(this).val());
        $(this).parent().children('input[name="alternativa[]"]').each(function () {
            input.push($(this).val());
        });
    });

    $.ajax({
        type: 'POST',
        url: '/enviaProva.php',
        dataType: "json",
        data: {questao: textarea, alternativa: input},
        success: function (res) {

        }
    });
});

the expected result in php would be:

$questao = isset($_POST['questao']) ? $_POST['questao'] : "";
$alternativa = isset($_POST['alternativa']) ? $_POST['alternativa'] : "";

if I give a var_dump in $questao returns me:

array(2) {[0]=> string(12) "primeira questao" [1]=> string(12) "segunda questao"}

in the alternative $returns me:

array(5) { [0]=> string(2) "a)" [1]=> string(2) "b)" [2]=> string(2) "a)" [3]=> string(2) "b)" [4]=> string(2) "c)" } 

and the alternatives of the first question are "a)" and "b)". And the second question is "a)", "b)" and "C)"

I’m not able to relate the two arrays inside php.

  • Can you give an example of the format you want to get? See HTML would be very useful too...

  • updated the question

  • You can also put the html related to a question and alternatives ?

  • OK I’ll put.

  • added the sample html

2 answers

0


You can create an array where each question is an object with the format

{
  pergunta: 'texto',
  alternativas: [
    'altern 1',
    'altern x'
  ]
}

You can get it like this:

$("body").on('click', 'button[name="enviaProva"]', function(e) {
  e.preventDefault();
  const perguntas = $('textarea[name="quest[]"]').get().map(function(el) {
    const alternativas = $(el)
      .parent()
      .children('input[name="alternativa[]"]')
      .get()
      .map(function(input) {
        return input.value;
      });

    return {
      pergunta: el.value,
      alternativas: alternativas
    };
  });
  
  console.log(JSON.stringify(perguntas));

  $.ajax({
    type: 'POST',
    url: '/enviaProva.php',
    dataType: "json",
    data: perguntas,
    success: function(res) {
      console.log(res);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
  <li><textarea name="quest[]" placeholder="Digite seu texto aqui." required=""></textarea>
    <input type="text" id="quest1" name="alternativa[]" value="a)" required="">
    <input type="text" id="quest1" name="alternativa[]" value="b)" required=""></li>

  <li><textarea name="quest[]" placeholder="Digite seu texto aqui." required=""></textarea>
    <input type="text" id="quest2" name="alternativa[]" value="a)" required="">
    <input type="text" id="quest2" name="alternativa[]" value="b)" required="">
    <input type="text" id="quest2" name="alternativa[]" value="c)" required=""></li>
</form>
<button name="enviaProva">Enviar</button>

  • hello friend could not implement this way, I updated the question once again I hope you can help me.

  • @Josérobertojuliana, I just saw the code you added. In PHP you want to handle the questions one by one or you want to send them all at once and the answer is related to all?

  • then I need to relate one by one to be able to insert into the bank, each question with its alternatives

  • @Josérobertojuliana ok, but you want to send one to one from the client to the/PHP server or you want to have everything in an array in PHP and handle the data in PHP/Server?

  • @Josérobertojuliana corrected an error in my answer, test now.

  • ok I’ll test now.

  • then Sergio, his code worked a part, he gets the alternatives in the desired sequence, but does not return the questions, Undefined questions.

  • @Josérobertojuliana tests my code as it is in the answer (you can run the example and click the button there). What the console shows is what you are looking for?

  • hello Sergio, yes it is 50% of the solution, just do not know how to pass also the questions, this "question: this.value" does not work here

  • has how to pass also the questions, is only passing the alternatives.

  • @Josérobertojuliana corrected, it should be el.value instead of this.value. Trying to help at night when you should be asleep is not ideal :)

  • you can help me to receive the data in php to save in the database?

Show 7 more comments

0

Hello thanks to the staff for the help in particular to the moderator Sergio I managed to pass everything to PHP, both the questions, and the alternatives and was like this:

    $("body").on('click', 'button[name="enviaProva"]', function (e) {
    e.preventDefault();
    var textarea = [];

    var perguntas = $('textarea[name="quest[]"]').get().map(function (el) {
        var alternativas = $(el)
                .parent()
                .children('input[name="alternativa[]"]')
                .get()
                .map(function (input) {
                    return input.value;
                });
        return {
            perguntas: el.value,
            alternativas: alternativas
        };
    });

    $.ajax({
        type: 'POST',
        url: '/enviaProva.php',
        dataType: "json",
        data: {perguntas: perguntas},
        success: function (res) {
            console.log(res);
        }
    });
});

This way I recover the data in PHP:

$questao = isset($_POST['perguntas']) ? $_POST['perguntas'] : "";
var_dump($questao);

and return me the values:

    array(2) {
  ["perguntas"]=>
  string(8) "primeira"
  ["alternativas"]=>
  array(2) {
    [0]=>
    string(2) "a)"
    [1]=>
    string(2) "b)"
  }
}
array(2) {
  ["perguntas"]=>
  string(7) "segunda"
  ["alternativas"]=>
  array(3) {
    [0]=>
    string(2) "a)"
    [1]=>
    string(2) "b)"
    [2]=>
    string(2) "c)"
  }
}

now as I do the insertion in the database, using the foreach it returns me a new array, as would be the insertion in the database in this case?

Browser other questions tagged

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