Javascript-форум (https://javascript.ru/forum/)
-   Серверные языки и технологии (https://javascript.ru/forum/server/)
-   -   Проблема с передачей данных формы (https://javascript.ru/forum/server/78396-problema-s-peredachejj-dannykh-formy.html)

stavatar@yandex.ru 07.09.2019 21:56

Проблема с передачей данных формы
 
https://se.ifmo.ru/~s264431/index.html

Проблема в том,что данные из формы index.html не передаются в handler.php
Код файла index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Сайт</title>
   <style>
  
   body 
   {
    background: #f6e8d7;
   }
   #helpMe
   {
    
      background: #f0f0f0; 
    width: 400px; 
    padding: 10px;
    border: 2px solid #000; 
	
   }
   input[type="submit"]	
   {
	  
	   border: 4px inset #100;
	    cursor: url(WorldOfWarCraft/arrow.cur),pointer;
	   
   }
   p b
   {
	   color:orange;
	   border: 1px inset #100;
	   box-shadow: 0 0 10px rgba(0,0,0,0.5);
	   background: #808080;
	   outline-style: outset;
   }
   img.rightfoto
   {
	margin: 0px; 
	float: right ;
   }
   .active {
  border: 1px solid red;
  color: red;
}
  </style>
 </head>


   
 <body>
<img class="img.rightfoto" src="image.png" " >
 <form method="GET" action="handler.php" class="formWithValidation" style="float: left;">


  <fieldset class="fieldset" style="width: 400px;">
 <h3 style="font-family: fantasy;font-stretch: inherit;font-weight: 0;" >ЗАГОЛОВОК </h5>
 <h5> 210001 <h3>
  <p><b name="textX"> X</b> 	       </p>


    
		   <div id="helpMe"> 
		   
		    <input type="button" class='checkboxxx'  name="InputX" value="-2"> 
				<input type="button" class='checkboxxx' name="InputX" value="-1.5">
				<input type="button" class='checkboxxx' name="InputX" value="-1">
				<input type="button" class='checkboxxx' name="InputX" value="-0.5">
				<input type="button" class='checkboxxx' name="InputX" value="0">
				<input type="button" class='checkboxxx' name="InputX" value="0.5">
				<input type="button" class='checkboxxx' name="InputX" value="1">
				<input type="button" class='checkboxxx' name="InputX" value="1.5">
				<input type="button" class='checkboxxx' name="InputX" value="2">
				 
				</div>
				
				<Br>
			
			
	<p><b> Y</b></p>
           
				<p><input type="text" class="Y"  maxlength="5" size="6" name="InputY" placeholder=" От -3 до  3"></p>
			
	
	<p><b> R</b></p>
	<p>
	        <p><input type="text" class="RRR"  maxlength="5" size="6" name="InputR" placeholder="  От 1 до  4"></p>
	
		 
    </p>
	<p><input type="submit"   class="validateBtn" ></p>
	   </fieldset>
	   
</form>

  <script>
  var SMSx;
  var SMSy;
  var SMSr;
  var conditionX=0;
  var form=document.querySelector('.formWithValidation');
  var button=document.querySelectorAll('.checkboxxx');
for (var buttoned of button)
 {
  buttoned.addEventListener('click', function (event) 
	{
         var X=event.clientX;	
	 var Y=event.clientY;
         button.forEach(i =>
			i.classList.remove('active'));

		
        this.classList.toggle('active');
	});
};



    function showError(container, errorMessage) {
      
     var msgElem = document.createElement('span');
      msgElem.className = "error-message";
      msgElem.innerHTML = errorMessage;
      container.appendChild(msgElem);
      
    }
 
    function resetError(container) {
            if (container.lastChild.className == "error-message") {
        container.removeChild(container.lastChild);
      }
    }
    
    form.addEventListener('submit', function (event) 
    {
    resetError(document.querySelector('.fieldset') );

      var elems = form.elements;
      if (elems.InputY.value) 
      {
        var reg=/^\d+[,]\d*$|^\d+$/ ;
				if(reg.test(elems.InputY.value))
				{	
       					SMSy=""
				}
                                else 
				{
					SMSy="Ошибка заполнения Y";
					event.preventDefault() ;

				}
				
        
      }
      else
      {
         SMSy=" Заполните Y <Br>";
         event.preventDefault() ;
      }
      
      if ((elems['InputX'][0].classList.contains('active'))||(elems['InputX'][1].classList.contains('active'))||
      (elems['InputX'][2].classList.contains('active'))||(elems['InputX'][3].classList.contains('active'))||
      (elems['InputX'][4].classList.contains('active'))||(elems['InputX'][5].classList.contains('active'))||
      (elems['InputX'][6].classList.contains('active'))||(elems['InputX'][7].classList.contains('active'))
      ||(elems['InputX'][7].classList.contains('active')))
      {
		        SMSx=""
		          
	    }
       	else
       	{
		        SMSx="<p style=\"font-size: 120%; font-family: monospace; color: #cd66cc\">Заполните  X </p> ";
            event.preventDefault() ;
	        }
	        if (elems.InputR.value) 
      		{
                                var reg=/^\d+[,]\d*$|^\d+$/ ;
				if(reg.test(elems.InputR.value))
				{	
       				SMSr=""
				}
                                else {
								SMSr="Ошибка заполнения R";
											   							event.preventDefault() ;

							}

        
     			 }
      		  else
                    {
                      SMSr=" Заполните  R <Br>";
                      event.preventDefault() ;
                    }
	       showError(document.querySelector('.fieldset') , SMSx+SMSy+SMSr);
      });
  </script>



</body>

</html>


И файл handler.php:
<html>

 <head>

  <title>Тестируем PHP</title>
 </head>
 <body>
 <?php

 if (!empty($_GET["InputX"])&&!empty($_GET["InputY"])&&!empty($_GET["InputR"])) 
 { 
     $X=$_GET["InputX"];
	 $R=$_GET["InputR"];
	 $Y=$_GET["InputY"];
	 echo " Получены новые вводные: имя ".$_GET["InputX"].", возраст  ".$_GET["InputY"]." лет и ".$_GET["InputR"]." ";
	 
     if(($X>-$R&&$X<0&&($Y>-$R)&&($Y<0))||($X<$R/2&&$X>0&&($Y>-$R/2)&&($Y<0)&&($X^2+$Y^2<$R/2*$R/2))||(($Y<$R)&&($X<$R/2)&&($Y<-2*$X+$R)))
	 {
		 echo " <b>Проверка пройдена.Точка попадает в график</b>";
		 
	 }else{ 
           echo " <b>Проверка не пройдена.Точка вне графика</b>";
	 }
	 
 } 
 else
 { 
     echo "Переменные не дошли. Проверьте все еще раз.";
 }
 

?>
<form method="GET" action="index.html">
    <input type="submit" value="Повторить ввод">
</form>
 </body>
</html>

Malleys 08.09.2019 04:06

stavatar@yandex.ru, то, что у вас проверяется по формуле в handler.php, на графике выглядит так...
Формулу внутри условной конструкции на 17-ой строке можно упростить до
$Y < $R && $X < $R / 2 && $Y < -2 * $X + $R


Если же нужно именно...

...то выражение будет таким
$X <= 0 && $Y >= 0 && $X ** 2 + $Y ** 2 <= $R ** 2 ||
$X <= 0 && $Y <= 0 && -2 * $X - $R <= $Y ||
$X >= 0 && $Y <= 0 && $X <= $R / 2 && $Y >= -$R


Кстати проверку можно сделать без PHP. Вы можете проверить эти значения сразу после ввода. Можно даже начертить точку на графике.

<!DOCTYPE html>
<html>

<head>
	<title>Сайт</title>
	<style>
		body {
			background: #f6e8d7;
		}

		label {
			display: block;
			margin: 0.5em;
		}
		
		svg {
			width: 300px;
			height: 300px;
		}

	</style>
</head>

<body>
	<form method="get" action="handler.php" style="display: inline-block; ">
		<label>
			X
<!--			<input type="range" min="-2" max="2" step="any" name="InputX" required>-->
			<select name="InputX" required>
				<option>-2</option>
				<option>-1.5</option>
				<option>-1</option>
				<option>-0.5</option>
				<option>0</option>
				<option>0.5</option>
				<option>1</option>
				<option>1.5</option>
				<option>2</option>
			</select>
		</label>

		<label>
			Y
<!--			<input type="range" min="-3" max="3" step="any" name="InputY" required placeholder="От -3 до  3">-->
			<input type="number" min="-3" max="3" step="any" name="InputY" required placeholder="От -3 до  3">
		</label>

		<label>
			R
<!--			<input type="range" min="1" max="4" step="any" name="InputR" required placeholder="От 1 до 4">-->
			<input type="number" min="1" max="4" step="any" name="InputR" required placeholder="От 1 до 4">
		</label>

		<output>
			<p id="info">&nbsp;</p>
			<svg xmlns="http://www.w3.org/2000/svg" viewBox="-60 -60 120 120">
				<defs>
					<marker id="head" orient="auto" markerWidth="6" markerHeight="6" refX="5.5" refY="4">
						<path d="M0,2 l6,2 l-6,2" stroke="currentColor" fill="none" stroke-width="0.75" />
					</marker>
					<marker id="stop" orient="auto" markerWidth="6" markerHeight="6" refX="0" refY="4">
						<path d="M0,2 v4" stroke="currentColor" fill="none" stroke-width="2" />
					</marker>
				</defs>
				
				<path fill="#3399ff" d="M0,-50 A50,50 0,0,0 -50,0 L-25,0 L0,50 L25,50 L25,0 L0,0"></path>
<!--				<path fill="#3399ff" d="M-200,-50 L0,-50 L25,0 L25,200"></path>-->
				
				<g marker-mid="url(#stop)" marker-end="url(#head)" stroke-width="0.5" stroke="black">
					<path d="M-60,0 L-50,0 L-25,0 L25,0 L50,0 L60,0" />
					<path d="M0,60 L0,50 L0,25 L0,-25 L0,-50 L0,-60" />
				</g>
				
				<g style="font: italic 5px serif;">
					<text x="55" y="-2.5">x</text>
					<text x="2.5" y="-55">y</text>
					
				</g>
				
				<g style="font: 5px serif;" text-anchor="middle">
					<text x="50" y="-2.5">R</text>
					<text x="25" y="-2.5">R/2</text>
					<text x="2.5" y="-48.75" text-anchor="start">R</text>
					<text x="2.5" y="-23.75" text-anchor="start">R/2</text>
				</g>
				
				<circle r="2" fill="none" stroke="red" id="dot"></circle>
				
			</svg>
		</output>
	</form>

	<script>
		addEventListener("submit", event => {
			event.preventDefault();
		});
		
		addEventListener("input", event => {
			const data = new FormData(document.querySelector("form"));
			const dot = document.querySelector("#dot");
			const info = document.querySelector("#info");
			
			const $X = Number(data.get("InputX"));
			const $Y = Number(data.get("InputY"));
			const $R = Number(data.get("InputR"));
			
//			const f =
//				$Y < $R && $X < $R / 2 && $Y < -2 * $X + $R
//			;
			
			const f =
				$X <= 0 && $Y >= 0 && $X ** 2 + $Y ** 2 <= $R ** 2 ||
				$X <= 0 && $Y <= 0 && -2 * $X - $R <= $Y ||
				$X >= 0 && $Y <= 0 && $X <= $R / 2 && $Y >= -$R
			;
			
			dot.cx.baseVal.value = $X / $R * 50;
			dot.cy.baseVal.value = -$Y / $R * 50;
			
			dot.setAttribute("fill", f ? "red" : "none");
			info.textContent = f ?
				"Проверка пройдена.Точка попадает в график" :
				"Проверка не пройдена.Точка вне графика"
			;
		});
		
	</script>
</body>
</html>

laimas 08.09.2019 04:09

Цитата:

Сообщение от stavatar@yandex.ru
данные из формы index.html не передаются в handler.php

Вы проверяли это? Не будет передаваться только одно - <input type="button" class='checkboxxx' .... Замените тип этого набора на что и положено, radio, и проблемы не будет.

$X=$_GET["InputX"];
$R=$_GET["InputR"];
$Y=$_GET["InputY"];

тем не менее далее

echo " Получены новые вводные: имя ".$_GET["InputX"].", ....

что только ради расчета объявление переменных, а на остальное табу?

stavatar@yandex.ru 08.09.2019 15:40

Цитата:

Сообщение от Malleys (Сообщение 512570)
stavatar@yandex.ru, то, что у вас проверяется по формуле в handler.php, на графике выглядит так...
Формулу внутри условной конструкции на 17-ой строке можно упростить до
$Y < $R && $X < $R / 2 && $Y < -2 * $X + $R


Если же нужно именно...

...то выражение будет таким
$X <= 0 && $Y >= 0 && $X ** 2 + $Y ** 2 <= $R ** 2 ||
$X <= 0 && $Y <= 0 && -2 * $X - $R <= $Y ||
$X >= 0 && $Y <= 0 && $X <= $R / 2 && $Y >= -$R


Кстати проверку можно сделать без PHP. Вы можете проверить эти значения сразу после ввода. Можно даже начертить точку на графике.

<!DOCTYPE html>
<html>

<head>
	<title>Сайт</title>
	<style>
		body {
			background: #f6e8d7;
		}

		label {
			display: block;
			margin: 0.5em;
		}
		
		svg {
			width: 300px;
			height: 300px;
		}

	</style>
</head>

<body>
	<form method="get" action="handler.php" style="display: inline-block; ">
		<label>
			X
<!--			<input type="range" min="-2" max="2" step="any" name="InputX" required>-->
			<select name="InputX" required>
				<option>-2</option>
				<option>-1.5</option>
				<option>-1</option>
				<option>-0.5</option>
				<option>0</option>
				<option>0.5</option>
				<option>1</option>
				<option>1.5</option>
				<option>2</option>
			</select>
		</label>

		<label>
			Y
<!--			<input type="range" min="-3" max="3" step="any" name="InputY" required placeholder="От -3 до  3">-->
			<input type="number" min="-3" max="3" step="any" name="InputY" required placeholder="От -3 до  3">
		</label>

		<label>
			R
<!--			<input type="range" min="1" max="4" step="any" name="InputR" required placeholder="От 1 до 4">-->
			<input type="number" min="1" max="4" step="any" name="InputR" required placeholder="От 1 до 4">
		</label>

		<output>
			<p id="info">&nbsp;</p>
			<svg xmlns="http://www.w3.org/2000/svg" viewBox="-60 -60 120 120">
				<defs>
					<marker id="head" orient="auto" markerWidth="6" markerHeight="6" refX="5.5" refY="4">
						<path d="M0,2 l6,2 l-6,2" stroke="currentColor" fill="none" stroke-width="0.75" />
					</marker>
					<marker id="stop" orient="auto" markerWidth="6" markerHeight="6" refX="0" refY="4">
						<path d="M0,2 v4" stroke="currentColor" fill="none" stroke-width="2" />
					</marker>
				</defs>
				
				<path fill="#3399ff" d="M0,-50 A50,50 0,0,0 -50,0 L-25,0 L0,50 L25,50 L25,0 L0,0"></path>
<!--				<path fill="#3399ff" d="M-200,-50 L0,-50 L25,0 L25,200"></path>-->
				
				<g marker-mid="url(#stop)" marker-end="url(#head)" stroke-width="0.5" stroke="black">
					<path d="M-60,0 L-50,0 L-25,0 L25,0 L50,0 L60,0" />
					<path d="M0,60 L0,50 L0,25 L0,-25 L0,-50 L0,-60" />
				</g>
				
				<g style="font: italic 5px serif;">
					<text x="55" y="-2.5">x</text>
					<text x="2.5" y="-55">y</text>
					
				</g>
				
				<g style="font: 5px serif;" text-anchor="middle">
					<text x="50" y="-2.5">R</text>
					<text x="25" y="-2.5">R/2</text>
					<text x="2.5" y="-48.75" text-anchor="start">R</text>
					<text x="2.5" y="-23.75" text-anchor="start">R/2</text>
				</g>
				
				<circle r="2" fill="none" stroke="red" id="dot"></circle>
				
			</svg>
		</output>
	</form>

	<script>
		addEventListener("submit", event => {
			event.preventDefault();
		});
		
		addEventListener("input", event => {
			const data = new FormData(document.querySelector("form"));
			const dot = document.querySelector("#dot");
			const info = document.querySelector("#info");
			
			const $X = Number(data.get("InputX"));
			const $Y = Number(data.get("InputY"));
			const $R = Number(data.get("InputR"));
			
//			const f =
//				$Y < $R && $X < $R / 2 && $Y < -2 * $X + $R
//			;
			
			const f =
				$X <= 0 && $Y >= 0 && $X ** 2 + $Y ** 2 <= $R ** 2 ||
				$X <= 0 && $Y <= 0 && -2 * $X - $R <= $Y ||
				$X >= 0 && $Y <= 0 && $X <= $R / 2 && $Y >= -$R
			;
			
			dot.cx.baseVal.value = $X / $R * 50;
			dot.cy.baseVal.value = -$Y / $R * 50;
			
			dot.setAttribute("fill", f ? "red" : "none");
			info.textContent = f ?
				"Проверка пройдена.Точка попадает в график" :
				"Проверка не пройдена.Точка вне графика"
			;
		});
		
	</script>
</body>
</html>

БОЛЬШОЕ спасибо!Теперь буду разбираться в этом коде,ибо со всем этия я познакомился недавно,я и про тег <output> узнал только сейчас.
Сам сайт это задание по вузу и там по условию надо,что бы открывалась новая страница с результатом(вообще там должна быть таблица в которой будут все результаты попадания/непопадания точки),так что передача данных на новую страницу ,а также проверка попадания/непопадания на php на новой странице сделано специально.Там же по условию координата X Должна быть именно Button и никакая другая,но на другом форуме мне уже подсказали,как передать данные


Часовой пояс GMT +3, время: 18:00.