2016-05-23 14 views
1

我對AJAX請求有麻煩,我不知道爲什麼。以下代碼似乎發送到整個網頁腳本(如我的警報框和控制檯中所示),而不是我的複選框值。任何人都可以向我解釋我做錯了什麼? 這是我的PHP複選框,具有由SQL生成的值,並沒有提交按鈕,使代碼設置爲從用戶改變運行:AJAX似乎是發送整個網頁腳本而不是數據

<form id="numberOrderForm" action="testdatabase.php" method="post"> 
    <div class="wrappers" id="multi-select1Wrapper"> 
     <h2>Area Code</h2> 
     <select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple"> 
      <?php 
       //The query asking from our database 
       $areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName` 
           FROM `AreaCodes` ac";                //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName' 

       $areaCodeResults = $conn->query($areaCodeSQL);              // put results of SQL query into this variable 

       if ($areaCodeResults->num_rows > 0) {                // if num_rows(from $results) is greater than 0, then do this: 
        // output data of each row 
           foreach($areaCodeResults as $areaCodeResult)          //for each item in $areCodeResults do this: 
            { 
             $areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them 
             $areaName = $areaCodeResult['AreaName'];         // get AreaName 
             $areaCode = $areaCodeResult['AreaCode'];         //get AreaCode 

             ?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables 
            } 
       } 

      ?> 
     </select> 
    </div> 
</form> 

這裏是我的jQuery AJAX代碼:

<script> 
     $('#multi-select1').on("change", function(){ 
      var areaCode = $(this).val(); 

      $.ajax({ 
       type:"POST", 
       url: "testdatabase.php", //my PHP database 
       data: "areacode=" + areaCode, 
       success: function(response){ 
       //do stuff after the AJAX calls successfully completes 
        alert (response); 
        console.log(response); 
       }, 
       error : function(xhr, status, error) { 
        alert(xhr.responseText); 
       } 
      }); 
     }); 

</script> 

回答

1

你的數據是不正確的一個。

取代:

data: "areacode=" + areaCode, 

有:

data: {"areacode": areaCode}, 

你還應該加上:enctype='multipart/form-data'到你的表單元素

-1

請jQuery的AJAX調用添加以下行

dataType: 'json' 
contentType: "application/json", 

添加上面的代碼後,您的代碼就像下面

​​
相關問題