K
K
Kn942342021-11-18 11:47:33
AJAX
Kn94234, 2021-11-18 11:47:33

how to change variable in js?

Good afternoon!
Mathematical calculators on the page. Each has a button that sends form data.
There is a function below. In the function, I parse a JSON array, such as {answer1: 16, answer2: 0, answer3: 12, etc.}
In the function, the number corresponding to the array key (answer1 - 1, answer2 -2, etc.) is passed to the count parameter .).
And on the page I need to display the array value corresponding to the calculator (the button that starts the script).
I need the result.answer_item array element to be selected depending on the passed count value,
those. result.answer1, or result.answer2, etc. But when I set answer_item to answer1 (or answer2), the value becomes a string, the array element reference result.answer_item( result.answer1) becomes undefined.
What can be done to make the answer variable dynamic and change depending on the count parameter?

$( document ).ready(function() {
    $("#btn1").click(
    function(){
      sendAjaxForm('formula1_result', 'formula1_form', 'math.php',1);
      return false; 
    }
  );
});

$( document ).ready(function() {
    $("#btn2").click(
    function(){
      sendAjaxForm('formula2_result', 'formula2_form', 'math.php',2);			
      return false; 
    }
  );
});

function sendAjaxForm(result_form, ajax_form, url, count) {
    $.ajax({
        url:     url, //url страницы (action_ajax_form.php)
        type:     "POST", //метод отправки
        dataType: "html", //формат данных
        data: $("#"+ajax_form).serialize(),  // Сеарилизуем объект
        success: function(response) { //Данные отправлены успешно
          result = JSON.parse(response);
        	console.log(result);						
          name_output_div= "#"+result_form;
          answer_item='answer'+count;	 	
          console.log(result.answer_item);	
          answer=result.answer_item;  ------------------- проблема здесь
          $(name_output_div).text('Ответ: '+answer); 	
          
    	},
    	error: function(response) { // Данные не отправлены
            $(name_output_div).text('Ошибка. Данные не отправлены.');
    	}
 	});
}


<body>
    <h2>Математические формулы</h2>
    <!---------------------- Квадрат суммы ------------------->
    <p><strong>Квадрат суммы:</strong></p>
    <form action="" method="post" id="formula1_form">
      <ul>
        <li class="math-item">
          <label> Число a:
            <input class="math-short-field" type="text" placeholder="2" name="formula1_a">
          </label>
        </li>
        <li>
          <label> Число b:
            <input class="math-short-field" type="text" placeholder="5" name="formula1_b">
          </label>
        </li>	
      </ul>			
      <button type="submit" aria-label="Вычислить квадрат суммы" id="btn1">Вычислить квадрат суммы</button>
    </form>	
    <div class="answer" id="formula1_result"></div>
    <!---------------------- Квадрат разности ------------------->
    <p><strong>Квадрат разности:</strong></p>
    <form action="" method="post" id="formula2_form">
      <ul>
        <li class="math-item">
          <label> Число a:
            <input class="math-short-field" type="text" placeholder="2" name="formula2_a">
          </label>
        </li>
        <li>
          <label> Число b:
            <input class="math-short-field" type="text" placeholder="5" name="formula2_b">
          </label>
        </li>	
      </ul>			
      <button type="submit" aria-label="Вычислить квадрат разности" id="btn2">Вычислить квадрат разности</button>
    </form>	
    <div class="answer" id="formula2_result"></div>


<?

//Квадрат суммы
if (isset($_POST["formula1_a"]) && isset($_POST["formula1_b"]) || isset($_POST["formula2_a"]) && isset($_POST["formula2_b"])             ) { 
  $a = $_POST["formula1_a"];
  $b = $_POST["formula1_b"];	
  $a2 = $_POST["formula2_a"];
  $b2 = $_POST["formula2_b"];
  
  $formula1 = pow($a,2) + 2*$a*$b + pow($b,2);
  $formula2 = pow($a2,2)- 2*$a2*$b2 + pow($b2,2);
}

  // Формируем массив для JSON ответа
    $result = array(
    	'answer1' => $formula1,
      'answer2' => $formula2
    ); 
    // Переводим массив в JSON		
    echo json_encode($result); 
?>


619613901d3e8903812042.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question