2017-12-27 16 views
0

내가 선택한 버튼을 기반으로 다른 값을 설정 한 다음 최종 버튼에 값을 설정하고 다음 PHP 페이지로 모두 제출하는 PHP 웹 사이트에 여러 버튼이 있습니다.html의 여러 버튼을 사용하여 내 웹 사이트의 값을 설정 한 다음 모든 데이터를 제출하는 버튼을 설정하는 방법은 무엇입니까?

<form id="formUploadFile" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post" > 
    <p> 
     <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>"> 
    </p> 

    <p align="left"> 
     <label for="file" >First, Choose your image!</label> 
     <input type="file" name="files[]" /> 
    </p> 

    <p> 
     <h5>Would you like to use colored pencils or paint?</h5> 
     <div class="btn-group"> 
      <button class="btn btn-primary" name="ToolChoice" value="0">Colored Pencils</button> 
      <button class="btn btn-primary" name="ToolChoice" value="1">Paint</button> 
      </div> 
    </p> 
    <p class="text-center"> 
     <h5>Then, Choose your Difficulty!</h5> 
      <div class="btn-group"> 
      <button type="submit" class="btn btn-success" name="DifficultyChoice" value="0" onclick="loadingCircle()">Kids</button> 
      <button type="submit" class="btn btn-success" name="DifficultyChoice" value="1" onclick="loadingCircle()">Novice</button> 
      <button type="submit" class="btn btn-success" name="DifficultyChoice" value="2" onclick="loadingCircle()">Intermediate</button> 
      <button type="submit" class="btn btn-success" name="DifficultyChoice" value="3" onclick="loadingCircle()">Advanced</button> 
      </div> 

    </p> 

    </form> 

내가 먼저 "ToolChoice"을 선택하고 자신의 "DifficultyChoice"를 선택하고 두 값이 모두에 게시하도록하기 위해 사용자가 원하는 : 그래서 나는 여기 폼의 내부 설정해야 버튼의 두 세트를 $ uploadHandler. 작성된 그러나 만 "DifficultyChoice는. PHP는 말에 난 그냥,

$difficulty=$_POST['DifficultyChoice']; 
$toolChoice=$_POST['ToolChoice']; 

나는 내가 toolchoice 위해 제출 사용하지 않는 때문에이 이해 사용하고 전송되는하지만 난 싶지 않아 별도로 각각의 값에 대한 PHP는 $의 uploadHandler를 실행합니다. 오히려 내가 설정하고 같은 시간에 전송 둘 필요가있다.

를 어떤 도움에 감사드립니다!

당신은 자바 스크립트를 사용하고있는 온 클릭 속성을 사용할 것

답변

0

제출 이벤트 처리시에는 javscript을 사용하십시오. 프로그램 상태의 저장은 다양한 방법으로 수행 될 수 있습니다. 이 예에서는 값을 저장하기 위해 두개 숨겨진 필드를 사용했을

<input type="hidden" name="DifficultyChoice" id="hiddDiff" value="-1" /> 
<input type="hidden" name="toolChoice" id="hiddTool" value="-1" /> 

나는 두 함수 changeDifficultyint 전달되는 changeTools 만들었고, 이들은 물론 hidden fields 값을 설정.

Hidden fields은 수신 PHP 파일로 전달되는 name을 가지고 있기 때문에 사용됩니다. 따라서 각 buttonnames을 사용할 필요가 없습니다. 대신 javascripttwo functionstwo hidden fields와 함께 당신을 위해 그것을 할 수 있습니다 :

편집

: 영업뿐만 아니라 수신 서버 측 요청 이후 내가 작업, 예를 들어 원래의 대답을 교체했다.

이 프로그램은 두 PHP 파일 a_test.phpb_tesp.php, 한 javascript 파일 a_test.js로 구성되어 있습니다. 이 예제가 작동하려면 모두 같은 폴더에 있어야합니다.

프로그램 순서 :a_test.phpa_test.js를 사용하여 b_test.phpPOST 데이터를 전송합니다. b_test.php이 데이터를 수신하고 유효성 검사를 시도합니다. 모든 것이 정상이면 이미지가 업로드되고, 그렇지 않으면 오류 메시지가 나타납니다.

파일 a_test.php :

<!DOCTYPE html> 
<html> 
<head> 
<title>Title of the document</title> 
<script src="a_test.js"></script> 
</head> 

<body> 
<form id="formUploadFile" name="formUploadFile" action="b_test.php" enctype="multipart/form-data" method="post" > 

    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>"> 

    <p align="left"> 
    <label for="file" >First, Choose your image!</label> 
    <input type="file" name="img_1" /> 
    </p> 

    <h5>Would you like to use colored pencils or paint?</h5> 
    <div class="btn-group"> 
     <input type="button" class="btn btn-primary" value="Colored Pencils" onclick="changeTools(0)" /> 
     <input type="button" class="btn btn-primary" value="Paint" onclick="changeTools(1)" /> 
    </div> 

    <h5>Then, Choose your Difficulty!</h5> 
    <div class="btn-group"> 
     <input type="button" class="btn btn-success" value="Kids" onclick= "changeDifficulty(0)" /> 
     <input type="button" class="btn btn-success" value="Novice" onclick="changeDifficulty(1)" /> 
     <input type="button" class="btn btn-success" value="Intermediate" onclick="changeDifficulty(2)" /> 
     <input type="button" class="btn btn-success" value="Advanced" onclick="changeDifficulty(3)" /> 
    </div> 

    <input type="hidden" name="difficultyChoice" id="hiddDiff" value="-1" /> 
    <input type="hidden" name="toolChoice" id="hiddTool" value="-1" /> 
</form> 
</body> 

</html> 

파일 a_test.js :

function changeDifficulty(number) 
{ 
    var toolChoice = parseInt(document.getElementById('hiddTool').value) 
    var difficulty = document.getElementById('hiddDiff'); 
    var form = document.getElementById('formUploadFile'); 
    difficulty.value = number; 

    // if the toolChoice is set 
    if(toolChoice != -1) 
    { 
     // Show the values, for testing purposes 
     console.log("Tools: " + toolChoice + " Difficulty: " + difficulty.value); 
     form.submit(); 
    } 
} 

function changeTools(number) 
{ 
    var difficulty = parseInt(document.getElementById('hiddDiff').value) 
    var toolChoice = document.getElementById('hiddTool'); 
    var form = document.getElementById('formUploadFile'); 
    toolChoice.value = number; 

    // If the difficulty is set 
    if(difficulty != -1) 
    { 
     console.log("Tools: " + toolChoice.value + " Difficulty: " + difficulty); 
     form.submit(); 
    } 
} 

파일 b_test.php :

<?php 

// make a function to check if `int` so you don't have to retype for each variable 
function checkIfInt($var) 
{ 
    // Here we use a fix to let `0` also be validated as `int` 
    if (filter_var($var, FILTER_VALIDATE_INT) || filter_var($var, FILTER_VALIDATE_INT) === 0) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 


function checkImageValidityAndUpload() 
{ 
    // Check if file was uploaded without errors 
    if($_FILES["img_1"]["error"] == 0) 
    { 
     // allowed image types 
     $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"); 
     // some (incoming) file properties 
     $filename = $_FILES["img_1"]["name"]; 
     $filetype = $_FILES["img_1"]["type"]; 
     $filesize = $_FILES["img_1"]["size"]; 

     // Verify file extension (here we are comparing the file extension to the keys of $allowed array) 
     $ext = pathinfo($filename, PATHINFO_EXTENSION); 
     if(!array_key_exists($ext, $allowed)) 
     { 
      echo "Error: Please select a valid file format.<br/>"; 
      return false; 
     } 

     // Verify file size - 5MB maximum (5MB is example, you can set anything) 
     $maxsize = 5 * 1024 * 1024; 
     if($filesize > $maxsize) 
     { 
      echo "Error: File size is larger than the allowed limit.<br/>"; 
      return false; 
     } 

     // Verify MYME type of the file (here we are comparing the file MYME type to the $allowed array values) 
     if(in_array($filetype, $allowed)) 
     { 
      // Check whether file exists before uploading it (upload/ is example folder, change to your image folder) 
      if(file_exists("upload/" . $_FILES["img_1"]["name"])) 
      { 
       echo $_FILES["img_1"]["name"] . " already exists.<br/>"; 
       return false; 
      } 
      else 
      { 
       move_uploaded_file($_FILES["img_1"]["tmp_name"], "upload/" . $_FILES["img_1"]["name"]); 
       return true; 
      } 
     } 
     else 
     { 
      echo "Error: There was a problem uploading your file. Please try again.<br/>"; 
      return false; 
     } 
    } 
    else 
    { 
     echo "Error: " . $_FILES["img_1"]["error"]."<br/>"; 
     return false; 
    } 
} 



// MAIN program starts here - Check if the form was submitted 
if($_SERVER["REQUEST_METHOD"] == "POST") 
{ 
    $tools = array("Colored Pencils", "Paint"); 
    $difficulties = array("Kids", "Novice", "Intermediate", "Advanced"); 

    // check if all needed variables are set and valid, and if the image is valid and uploaded successfully 
    if(isset($_POST['difficultyChoice']) && isset($_POST['toolChoice']) && isset($_FILES['img_1']) && 
     checkIfInt($_POST['difficultyChoice']) && checkIfInt($_POST['toolChoice']) && 
     checkImageValidityAndUpload()) 
    { 
     $diff = intval($_POST['difficultyChoice']); 
     $tool = intval($_POST['toolChoice']); 
     echo 'Tools choice: '.$tools[$tool].' Difficulty choice: '.$difficulties[$diff].'<br/>'; 
     echo 'image has been uploaded successfully'; 
     // do something 
    } 
    else 
    { 
     echo 'Something went wrong. Program will not continue'; 
     die(); 
    } 
} 
else 
{ 
    echo 'There was no POST request.'; 
    die(); 
} 
?> 
다음

코드입니다
+0

나는 이것이 쓰여지는 방식으로, 다른 버튼을 선택할 때마다 버튼이 -1로 재설정되도록한다고 생각합니다. 각 함수의 시작 부분에서 요소 ID로 변수를 설정하고 요소 ID가있는 유일한 영역은 값이 -1로 설정 되었기 때문입니다. 또한, PHP 사이트에서 이러한 버튼의 가치를 얻는 방법은 무엇입니까? – clutch1020

+0

@ clutch1020 이제 이미지, difficultChoice 및 toolChoice를'b_test.php'라는 파일에 제출할 예제 파일'a_test.php'에 대한 예제 (방금 테스트했습니다)를 업로드 할 것입니다. 파일'a_test.php'는 자바 스크립트 파일'a_test.js'를 사용합니다. 이 파일들을 모두 같은 폴더에 넣으십시오. 'b_test.php'에서 남긴 주석을 읽고 프로그램이 수신 측에서 어떻게 작동하는지 이해하십시오. 폴더가 존재하는지 프로그램이 확인하지 않기 때문에'upload folder'를 기존 폴더로 설정하십시오. – Ivan86

+0

@ clutch1020 확인. 나는 편집했다. 코드를 새로운 파일에'복사/붙여 넣기 (copy/paste) '하고 파일 이름을 지정하여 작업 한 것을 확인하십시오. 이미지를 업로드하는 것은 보안 위험이 크고 올바르게 검사해야하기 때문에 서버 측 코드의 양 ('b_test.php')이 필요합니다. – Ivan86

0

이 함수는 버튼의 값을 실제 PHP 페이지로 제출할 때 활성화되어 있는지 확인하기 위해 필요한 값으로 변경합니다. 같은 이름의 속성을 가진 톤은 절대로 작동하지 않습니다. 오히려 각각에 대해 각각 다른 이름 속성을 부여하고 클릭시 JavaScript를 사용하여 값을 "활성"으로 변경 한 다음 전송 된 모든 $ _POST를 모두 확인하려고합니다. 예를 들어, 첫 번째 난이도를 "Difficulty1"로 지정하십시오. if ($_POST['Difficulty1'] === 'active') { // They chose this difficulty }

+0

사실, 당신이 필요로하는 것을 잘못 읽었습니다. 따라서 기본적으로 DifficultyChoice의 다른 버튼은 달라지기를 원하지만 현재 값이 아니라 JavaScript를 사용하여 ToolChoice로 사용자가 선택한 항목으로 변경하십시오. 그렇다면 모든 어려움에 대한 가치가 당신이 얻는 데 필요한 도구가 될 것입니다. –

관련 문제