2016-10-14 3 views
0

7 개의 jquery 체크 박스 값을 ajax를 통해 PHP로 보내려고합니다. 값을 배열에 넣고 아약스 배열을 serialize하려고합니다. 궁극적으로, 나는 MySQL WHERE 절의 조건으로 체크 박스의 값을 사용하고 싶다. 내 아약스 성공적으로 완료하지만 배열의 값은 항상 사용하려고 어떤 메서드에 상관없이 null입니다.ajax를 통해 PHP로 확인란 값을 보내면 null이됩니다.

코드 : 참고 : 답변에 제공된 제안 된 수정 내용을 반영하도록 여기에 코드를 업데이트했습니다.

내 HTML 코드 :

<label for="prestage_select">Prestage</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="prestage_select" class="revenuechbxs" value="Prestage"> 


<label for="validation_select">Validation</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="validation_select" class="revenuechbxs" value="Validation"> 


<label for="scheduling_select">Scheduling</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="scheduling_select" class="revenuechbxs" value="Scheduling"> 


<label for="production_select">Production</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="production_select" class="revenuechbxs" value="Production"> 


<label for="needsBOL_select">Needs BOL</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="needsBOL_select" class="revenuechbxs" value="Needs BOL"> 


<label for="shpAcct2Close_select">Shipped: Account to Close</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="shpAcct2Close_select" class="revenuechbxs" value="Shipped: Acctg. To Close Out"> 


<label for="movedToComplete_select">Moved to Complete for Selected Period</label> 
<input type="checkbox" name="revenue_checkboxes[]" id="movedToComplete_select" class="revenuechbxs" value="Complete"> 

내 아약스 코드 :

j("#create_submit").click(function(){ 

    //send Revenue Data values to php using ajax. 
        var revenuechbxarray = j('.revenuechbxs:checked').val(); 
        var revenuefrom = j('#revenuefrom').val(); 
        var revenueto = j('#revenueto').val(); 

        j.ajax ({ 
         method: 'POST', 
         url: "revenue_report.php", 
         data: { revenuefromtext: revenuefrom, revenuetotext: revenueto, revenuechbx: revenuechbxarray }, 
         success: function(response) { 
          j('#fieldset_ReportDiv').html(response); 
          } 
        }); 

      console.log(revenuechbxarray); 

내 PHP 코드 : 나는에 값을 전송하기 위해 몇 가지 제안을 시도

<?php 

include('inc.php'); 


//Get date range. 

$revenuefromajax=$_POST['revenuefromtext']; 
$revenuetoajax=$_POST['revenuetotext']; 

$revenuefromstring = strtotime($revenuefromajax); 
$revenuetostring = strtotime($revenuetoajax); 

$revenuefrom=date("Y-m-d", $revenuefromstring); 
$revenueto=date("Y-m-d", $revenuetostring); 


//Get selected Status Values. 

$revenue_check = $_POST['revenuechbx']; // 
print_r($revenue_check); //displays result of one checkbox (the first selected on) but not more than one... 


//connect to the database 
$conn = new mysqli($servername, $username, $password, $dbname); 

// Check connection 
if(mysqli_connect_errno()) { 
    printf('Could not connect: ' . mysqli_connect_error()); 
    exit(); 
} 

//echo 'MySQL Connected successfully.'."<BR>"; 


$conn->select_db("some database name"); /////Database name has been changed for security reasons///////// 

if(! $conn->select_db("some database name")) { 
    echo 'Could not select database. '."<BR>"; 
} 

// echo 'Successfully selected database. '."<BR>"; 

//Select Data and Display it in a table. 


$sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice/((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice)/lineitems.quantity), 2) AS avgunitrevenue 
    FROM clients 
    INNER JOIN invoices ON clients.id = invoices.clientid 
    INNER JOIN lineitems ON invoices.id = lineitems.invoiceid 
    WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' 
    ORDER BY invoices.id DESC"; 


$result = $conn->query($sql); 


echo "<table id='revenueReportA' align='center' class='report_DT'> 
<tr> 

<th>Customer</th> 
<th>SG</th> 
<th>Revenue</th> 
<th>SQ FT</th> 
<th>AVG Revenue Per SQ FT</th> 
<th>Number of Units</th> 
<th>AVG Revenue Per Unit</th> 
</tr>"; 


if ($result = $conn->query($sql)) { 

    // fetch associative array 
    while ($row = $result->fetch_assoc()) { 

    echo "<tr>"; 
    echo "<td>" . $row['company'] . "</td>"; 
    echo "<td>" . $row['id'] . "</td>"; 
    echo "<td>" ."$". $row['totalprice'] . "</td>"; 
    echo "<td>" . $row['sqft'] ."&nbsp;&nbsp;". "ft<sup>2</sup>". "</td>"; 
    echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>"; 
    echo "<td>" . $row['qty'] . "</td>"; 
    echo "<td>" ."$". $row['avgunitrevenue'] . "</td>"; 
    echo "</tr>"; 
    } 

    echo "</table>"; 

     //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

    //Free the result variable. 
    $result->free(); 
} 

//Close the Database connection. 
$conn->close(); 


?> 

PHP는하지만 값은 항상 null입니다.

참고 : revenueto 및 revenuefrom date에 대한 다른 아약스 요청을 포함했습니다. 이 호출은 성공적이며 내 테이블은 해당 날짜를 기준으로 올바르게 표시됩니다. 나는 단지 날짜와 같은 페이지에서 선택한 체크 박스의 실제 값을 가져올 수 없다. 클래스가하지 않는 체크 박스 단계

HTML 코드

<input class="revenue" type="checkbox" name="revenue_checkboxes[]" id="production_select" value="Production"> 

세트 확인란 이름으로 코드 단계에서

+0

당신이 직렬화 된 문자열'revenuechbxarray'를 기록 할 수 있습니다 : – xpuc7o

+0

2 개의 ajax 호출을 보았습니다. 첫 번째 것은 체크 박스 데이터를 보내는 곳이 아니며 성공 함수가 없습니다 – Dranes

답변

2

는 클래스 선택기를 사용하는 배열을 추가하고 자바 스크립트 코드로 공통 클래스 수익 추가 및 선택기 사용자 추가

Ajax 코드

var revenuechbxarray = $('.revenue:checked').val(); 

PHP 코드 :

$revenue_check = $_POST['revenuechbx']; // this is array 

당신이 사용자가이 배열로 json_encode는 JSON 문자열을 설정하고 데이터베이스를 변환 할 수 있습니다.

j('[name=revenue_checkboxes]:checked').serialize() 
0

일부 변경 속성 동안

+0

감사합니다! 이제 console.log()에서 첫 번째 체크 박스의 값을 볼 수 있습니다. 그러나 다른 확인란을 볼 수 없습니다. 딱 하나만. json_encode를 사용하면 MySQL 코드의 각 확인란의 값을 가져와 사용할 수 있습니까? 그렇다면 json_encode의 예제를 제공 할 수 있습니까? – rdimouro

0

는 이름으로 확인란을 선택하려면?
+1

이 코드가 OP를 돕는 이유에 대한 설명을 추가하십시오. 이렇게하면 미래의 시청자가 배울 수있는 답을 제공하는 데 도움이됩니다. 자세한 내용은 [답변]을 참조하십시오. –

관련 문제