V
V
Valery2021-06-20 12:17:49
AJAX
Valery, 2021-06-20 12:17:49

How to send javascript code result to db?

And so I decided for a long time whether to create this topic or not, but still decided. Because I'm at a dead end and I don't know where to turn anymore. In general, there is a test (if you can call it that) with a working javascript code in which the test result is shown. But I can't synchronize (probably I picked this word correctly) the data of this script in the database. I only know that this can be done with ajax, but I can't do it. I have a database, I need to synchronize data in it. I hope someone understood what I wrote. If there are any questions, then ask. And one more thing... I have sketches of ajax and php code (maybe this will help somehow).

This is our questionnaire itself (the questionnaire is much larger, but I put up part of it. If you need to continue it, then I will throw it off).

<form method="POST" action="otpravka.php" id="form">
    <section class="table_1">
        <table class="iksweb" name="checkbox">
            <tbody>
                <tr>
                    <td rowspan="3"><b>История компании «Mc donald's»</b>
                        <h3 class="the">Кто основал компанию «Mc donald's»?</h3>   
                        <section class="conteiner">
                            <div class="checkbox">
                                <input type="checkbox" class="i-6" id="i6" value="0" name="formDoor[]">
                                <label for="i6" tabindex="12">Роналд Макдоналд</label>     
                            </div>
                            <div class="checkbox">
                                <input type="checkbox" class="i-6" id="i7" value="0" name="formDoor[]">
                                <label for="i7" tabindex="13">Рэй Крок</label>     
                            </div>
                            <div class="checkbox">
                                <input type="checkbox" class="i-6" id="checkbox_68" value="1" name="formDoor[]">
                                <label for="checkbox_68" tabindex="14">Братья Дик и Мак Макдоналд</label>     
                            </div>
                            <div class="checkbox">
                                <input type="checkbox" class="i-6" id="checkbox_170" value="0" name="formDoor[]">
                                <label for="checkbox_170" tabindex="14">Клинт Иствуд</label>     
                            </div>
                            <div class="out-block out-6"></div>
                        </section>
                    </td>     
                </tr>
            </tbody>
        </table>
    </section>
    
    <div class="dsw">
        <button class="b-6" tabindex="11" id="btn-1" type="submit" name="formSubmit">Результат</button>
    <div>


Here we have js and ajax code (which is most likely not correct).
/* Главный скрипт формы (опросника) */
 
const form = document.querySelector('#form')
form.addEventListener('submit', onSubmit)
 
function onSubmit (event) {
  event.preventDefault()
 
  let listCheckbox = document.querySelectorAll('.i-6')
  listCheckbox = [...listCheckbox]
  
 
  // Проверяем выбран ли хотябы один ответ
  if (!listCheckbox.some(checkbox => checkbox.checked)) {
    alert('Вы не выбрали ни одного ответа')
  }
  
  else{
    form.addEventListener('submit', onSubmit)
    alert('Вы подтверждаете действие?');
  }
  // Узнаем сколько всего правильных ответов
  const rightAnswersCount = listCheckbox.filter(checkbox => Number(checkbox.value) === 1).length
 
  // Узнаем сколько всего не правильных ответов
  const wrongAnswerCount = listCheckbox.length - rightAnswersCount
 
  // Узнаем количество правильных ответов
  const rightAnswers = listCheckbox.filter(checkbox => Number(checkbox.value) === 1 && checkbox.checked).length
 
  // Узнаем количество не правильных ответов
  const wrongAnswer = listCheckbox.filter(checkbox => Number(checkbox.value) === 0 && checkbox.checked).length
 
  // Уведомляем пользователя
  alert(`Вы выбрали ${rightAnswers} вариантов из ${rightAnswersCount} правильных`);
  /*alert(`Вы ответили не правильно на ${wrongAnswer} из ${wrongAnswerCount}`)*/
 
  //Вывод ответа с процентами
  alert(`Процент правильных ответов: ${(rightAnswers / rightAnswersCount) * 100}`);
  /*alert(`Процент неправильных ответов: ${(wrongAnswer / wrongAnswerCount) * 100}`)*/
 
}
 
/* Скрипт правильных и неправильных ответов */
let button = document.getElementById('btn-1');
button.addEventListener('click', function(e) {
  document.querySelectorAll('.i-6').forEach(item => {
    let chekcbox = item.closest('div');
    if (item.checked && Number(item.value)) {
      chekcbox.classList.add("right");
      chekcbox.classList.remove("false");
    } else if (item.checked) {
      chekcbox.classList.add("false");
      chekcbox.classList.remove("right");
    } else {
      chekcbox.classList.remove("right");
      chekcbox.classList.remove("false");
    }
  })
});
 
 $.ajax({
            url: 'otpravka.php',
            type: 'POST',  
            data: chekcbox, 
            beforeSend: ()=>{}, 
           
            success: (data)=>{
                
                console.log(data);
            },
            
            error: (xhr)=>{
                console.log(xhr);
            },
            
            complete: ()=>{
                
            }
        });
    });


Here is the php code where the data is sent (I know that in the database connection you need to enter your data. I just don't want to show them. Otherwise, the data corresponds to the connection).
<?php
// подключение к бд
$link = mysqli_connect('localhost', 'db_user', 'password', 'db_name');
 
$name = $_POST['name']; 
$count = $_POST['count'];
$query = "INSERT INTO table (`name`,`count`) VALUES ('{$name}','{$count}')";
$result = mysqli_query($link, $query);
 
// вывести результат
print_r($result);
?>


Well, something like this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aricus, 2021-06-21
@Aricus

To send from js to database:
js -> ajax with variables -> php file -> db.
To send from database to js:
page -> script -> write variables in js.
To request data from the database via ajax:
js -> ajax -> php file that returns data from the database (string, or JSON) -> processing the ajax result.
The question is too general. At what stage do the problems arise?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question