通过json

时间:2018-01-21 16:40:21

标签: php json

我正在尝试从我的php文件中检索两个值到我的ajax但我不能。我尽了最大努力然后我能够做到这一点,但两个值都显示在我的页面(txtbox)中。

我需要使用json但不知何故我卡住了

<!DOCTYPE html>
<html lang="en">
<!--<meta charset="UTF-8">-->

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Oswald">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open Sans">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="assets/js/jquery-1.11.1.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
<script src="jquery.min.js"></script>
<script src="assets/js/scripts.js"></script>

<title>my test</title>    


</select>

    <script type="text/javascript">
    $(document).ready(function(){
        $('#Consumptions').on('change',function(){
            var ConsumptionsID = $(this).val();
            if(ConsumptionsID){
                $.ajax({
                    type:'POST',
                    url:'ajaxData.php',
                    data:'Consumption_id='+ConsumptionsID,
                    success:function(html){
                        $('#tariff').html(html);
                        $('#myamount_period').html('<option value="">Select tariff first</option>'); 
                    }
                }); 
            }else{

                $('#tariff').html('<option value="">Please select consumptions first</option>');
                $('#myamount_period').html('<option value="">Please select tariff first</option>'); 
            }
        });

        $('#tariff').on('change',function(){
            var tariffID = $(this).val();
            if(tariffID){
                $.ajax({
                    type:'POST',
                    url:'ajaxData.php',
                    data:'tariff_id='+tariffID,
                    success:function(html){
                        $('#myamount_period').html(html);
                    }
                }); 
            }else{
                $('#myamount_period').html('<option value=""> Select tariff first</option>'); 
            }
        });

        $('#myamount_period').on('change',function(){

            var amid = $(this).val();

            if(amid){
                $.ajax({
                    type:'POST',
                    url:'ajaxData.php',
                    data:'myamount_period=' +amid,
                    success:function(html){
                        $('#rateid').val(html);
                    }
                }); 
            }else{



            }       

        });

    });
 </script>

    <!-- Start Dispalying function in comboboxs for Water --> 

    <script type="text/javascript">
    $(document).ready(function(){
        $('#area').on('change',function(){
            var areaID = $(this).val();
            if(areaID){
                $.ajax({
                    type:'POST',
                    url:'ajaxwater.php',
                    data:'area_id='+areaID,
                    success:function(html){
                        $('#water').html(html);
                        $('#mymethos').html('<option value="">Please select water type first</option>'); 
                    }
                }); 
            }else{

                $('#water').html('<option value="">Please select area first</option>');
                $('#methods').html('<option value="">Please select Water Type First</option>'); 
            }
        });

        $('#water').on('change',function(){
            var waterID = $(this).val();
            if(waterID){
                $.ajax({
                    type:'POST',
                    url:'ajaxwater.php',
                    data:'water_id='+waterID,
                    success:function(html){
                        $('#mymethos').html(html);
                    }
                }); 
            }else{
                $('#mymethos').html('<option value="">Please select water type first</option>'); 
            }
        });

                    $('#mymethos').on('change',function(){
                      var mymethos_ID = $(this).val();
                      if(mymethos_ID)
                      {
                      $.ajax({
                            type:'POST',
                            url:'ajaxwater.php',
                            data:{mymethos: mymethos_ID}, // passes data better
                            dataType: 'json',                  // tells ajax what to expect in return
                            success: function(data) {
                                $('#water_r').val( data.methods_rate_rate ); // set by data object value
                                $('#tranprice').html( data.methods_rate_transp );
                            } 
                        }); 
                                                  }
                                    else
                                    {
                                     alert("Please Select Methods");

                                }
                               });

                              });

</script> <!-- End Displaying function in combobox for Water--> 

<script>  <!-- This function for reset ->
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

<!-- Include database configuration file & define varibales -->
<?php
include('dbConfig.php');
$cost="";
$Req_Ele="";
$Req_Ele="";


/*Water (cal btn) */
$cost_water="";
$tran_charge="";

if(isset($_POST['S2'])){
$tranpricing=$_POST['tranprice'];
$rate_w=$_POST['rate_water'];

}  

?>


    <body>  <!-- load all form as default (Browser refresh behaviour)-->
    <head>

        <!-- CSS -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
        <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="assets/css/form-elements.css">
        <link rel="stylesheet" href="assets/css/style.css">

        <!-- Favicon and touch icons -->
        <link rel="shortcut icon" href="assets/ico/favicon.png">
        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
        <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">

        </head>


        <!-- Top content -->

   <div class="inner-bg"> 
          <div class="container">

                <header>
                    <div class="logo"></div>
                   <span class="subtitle ng-binding" ng-show="header.subtitle" ng-bind="header.subtitle" 
                   style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" unselectable="on" onselectstart="return false;" onmousedown="return false;">
                       </span>  
                </header>

                <div class="content" id="content"> 
                     <div class="row">
                        <div class="col-sm-8 col-sm-offset-2 text">
                            <h1><b> Retrieve multi values from php to ajax .. </b></h1>
                            <div class="description">
                                <p>

                                </p>
                            </div>
                        </div>
                    </div>

                <div class="row">
                        <div class="col-sm-5">
                            <!-- Top form stop click also by style-->
                    <div class="form-box ">
                         <div class="form-top" style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" unselectable="on" onselectstart="return false;" onmousedown="return false;">

                         </div>


                    </div>
                        </div>

                <div class="col-sm-1 middle-border"></div>
                    <div class="col-sm-1"></div>
                        <div class="col-sm-5">
                            <div class="form-box">
                                <div class="form-top">

                           <div class="form-bottom">

                                <form name="myform2" method ="Post" action="">
                                    <select name="area" id="area">
                                        <option value="">Select Area:</option>
                                                <?php

                                                $query = $db->query("SELECT * FROM area WHERE status = 1 ORDER BY area_name ASC");
                                                //Count total number of rows
                                                $rowCount = $query->num_rows;

                                                 if($rowCount > 0){
                                                while($row = $query->fetch_assoc()){ 
                                                echo '<option value="'.$row['area_id'].'">'.$row['area_name'].'</option>';
                                                }
                                                 }else{
                                                echo '<option value="">Area not available</option>';
                                                }
                                                ?>

                                    </select>

                                    <select name="water" id="water">
                                    <option value="">Select Water Type:</option>
                                    </select></br>

                                    <select name="mymethos" id="mymethos">
                                    <option value="">Select Taken Method:</option>
                                    </select> 

                                        <div class="form-group">
                                            <div class="inputWithIcon"><input type="text" id="water_r" name="water_r" placeholder="Water Rate (OMR/m3):" readonly>
                                            <i class="fa fa-bar-chart" aria-hidden="true"></i></input></div> 
                                        </div>
                                        <input type="text" id="tranprice" name="tranprice" placeholder="Transportation Charge (OMR)" onkeypress="return isNumberKey(event)" readonly> 
                                        <input type="text" id="Req" name="num1" placeholder="Required Water (m3)" onkeypress="return isNumberKey(event)"> </br>   
                                        <input type="text" id="cost" name="cost_num" placeholder="Cost (.OMR)"  value="<?php echo $cost_water; ?>" readonly>  
                                        </br><input  name="S2" class="btn" type="submit" value="Calculate">


                                </form>  <!-- End of form 2 content-->
                            </div>  
                        </div>
                    </div>
                </div>
                </div>
        </div>
    </div>
    </body>
</html>

这是我的php文件。 (两个值都来自DB)。

<?php

include('dbConfig.php');  

if(isset($_POST["area_id"]) && !empty($_POST["area_id"])){

    $query = $db->query("SELECT * FROM water_type WHERE area_id =".$_POST['area_id']." AND status = 1 ORDER BY water_name desc");
    $rowCount = $query->num_rows;


    if($rowCount > 0){
        echo '<option value="">Please select water type</option>';
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['water_id'].'">'.$row['water_name'].'</option>';

        }
    }else{
        echo '<option value="">Water type not available</option>';
    }
}

if(isset($_POST["water_id"]) && !empty($_POST["water_id"])){

    $query = $db->query("SELECT * FROM methods_rate WHERE water_id= ".$_POST['water_id']." AND status = 1 ORDER BY methods_rate_name ASC");


    $rowCount = $query->num_rows;


    if($rowCount > 0){
        echo '<option value="">Please select water type</option>';
        while($row = $query->fetch_assoc()){ 

            echo '<option value="'.$row['methods_rate_id'].'">'.$row['methods_rate_name'].'</option>';
        }
    }else{
        echo '<option value="">Water type not available</option>';
    }
}

if ( !empty($_POST["mymethos"]) ) {// only need to check for empty (isset is needless)
    $query = $db->prepare("SELECT * FROM methods_rate 
                           WHERE methods_rate_id = ? AND status = 1");
    $query->bind_param('s',$_POST['mymethos']);// sql injection prevention!
    $query->execute();
    if ($query->num_rows > 0) {
        echo json_encode( $stmt->fetch_assoc() );
              // fetch one row since your form is 
              // not set to handle more than one row
              // outputs as json object for use in js 
    }
}

?>

这是我需要的屏幕截图。

enter image description here

这是我创建的数据库表:

-- ===========================================
-- Table structure for table `amount_period`
-- ===========================================

CREATE TABLE `amount_period` (
  `Amount_period_id` int(11) NOT NULL,
  `Amount_period_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `tariff_id` int(11) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active',
  `ele_rate` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT;


-- Dumping data for table `amount_period`


INSERT INTO `amount_period` (`Amount_period_id`, `Amount_period_name`, `tariff_id`, `status`, `ele_rate`) VALUES
(1, 'Period: Sep-Apr', 1, 1, 0.012),
(2, 'Period: May-Aug', 1, 1, 0.024),
(3, 'All Months', 2, 1, 0.02),
(5, 'Using 33 KV', 4, 1, 0.028),
(6, 'Using 132 KV', 5, 1, 0.02);



-- =========================================== 
 --Table structure for table `area`
 -- =========================================== 

CREATE TABLE `area` (
  `area_id` int(4) NOT NULL,
  `area_name` varchar(200) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- Dumping data for table `area`


INSERT INTO `area` (`area_id`, `area_name`, `status`) VALUES
(1, 'Port', 1),
(2, 'Freezone', 1);



-- =========================================== 
-- Table structure for table `methods_rate`
-- =========================================== 

CREATE TABLE `methods_rate` (
  `methods_rate_id` bigint(20) UNSIGNED NOT NULL,
  `methods_rate_name` varchar(200) NOT NULL,
  `status` int(11) NOT NULL DEFAULT '1',
  `water_id` int(11) NOT NULL,
  `methods_rate_rate` double NOT NULL,
  `methods_rate_transp` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- Dumping data for table `methods_rate`


INSERT INTO `methods_rate` (`methods_rate_id`, `methods_rate_name`, `status`, `water_id`, `methods_rate_rate`, `methods_rate_transp`) VALUES
(1, 'Normal', 1, 1, 0.77, 10),
(2, 'Take or Pay', 1, 2, 0.93, 77),
(3, 'Volumetric Charge', 1, 2, 1.145, 78),
(4, 'Excess Volume', 1, 2, 1.6, 68),
(5, 'Normal', 1, 3, 0.57, 33),
(6, 'Normal', 1, 4, 0.77, 434),
(7, 'Take or Pay', 1, 5, 1.202, 144),
(8, 'Excess Volume', 1, 6, 12, 20);




-- =========================================== 
-- Table structure for table `water_type`
-- =========================================== 

CREATE TABLE `water_type` (
  `water_id` bigint(20) UNSIGNED NOT NULL,
  `water_name` varchar(100) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1',
  `area_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `water_type`
--

INSERT INTO `water_type` (`water_id`, `water_name`, `status`, `area_id`) VALUES
(1, 'Potable - P', 1, 1),
(2, 'Process - P', 1, 1),
(3, 'Domestic Waste Water - P', 1, 1),
(4, 'Potable - F', 1, 2),
(5, 'Process - F', 1, 2),
(6, 'Domestic Waste Water - F', 1, 2);



-- -- =========================================== 
-- Indexes for table `amount_period`
-- =========================================== 


--
-- Indexes for table `methods_rate`
--
ALTER TABLE `methods_rate`
  ADD UNIQUE KEY `methods_rate_id` (`methods_rate_id`);

 --
-- Indexes for table `water_type`
--
ALTER TABLE `water_type`
  ADD UNIQUE KEY `water_id` (`water_id`);

-- AUTO_INCREMENT for table `methods_rate`
--
ALTER TABLE `methods_rate`
  MODIFY `methods_rate_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

-- AUTO_INCREMENT for table `water_type`
--
ALTER TABLE `water_type`
  MODIFY `water_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

1 个答案:

答案 0 :(得分:0)

我可以告诉你两个方法,一个是make和编码的json字段并解析它就像

    if($rowCount > 0){
            while($row = $query->fetch_assoc()){ 


$data = [];
$data['value1'] = $row['methods_rate_rate'];
$data['value2'] = $row['methods_rate_transp'];
             return json_encode($data);

now parse the value and use wherever you want    

            }

第二个选项是返回html,而不是在你的html partial上发送这些值,然后在响应中返回相同的html并附加它。