2017-02-10 9 views
0

まず、趣味として、Web開発の基本を学び始めたばかりです:html、css、javascript、php。 複数の選択ボックス条件を持つAjaxリクエスト

は、私はデータベースクエリを使用してWebページを実装しようとしていると、いくつかのdificultiesが発生している:

誰かがそれをはるかに高く評価されるだろう続行するためにどの道に私を啓発することができれば。

あなたは私のためにコード全体を書くのではなく、はい、いくつかのヒントと手掛かりを示してください。

Id、items、price1、price2、price3のテーブルがあります。

多くの検索の後、私は選択リスト上のすべてのアイテムを動的にロードし、ajax呼び出しで選択したアイテムに基づいて、変更時イベントでdivに(price1)を表示しました。

この値段は、3つの値(a、b、c)と(yesまたはno)の2つの選択リストに基づいて更新する必要があります。

選択リスト2が(a)であり、選択リスト3が(yes)の場合、表示される価格は(price2)です。選択リスト2が(b)であり、リスト3が選択されている場合(yes)、表示される価格は(price3)であり、リスト3オプションが選択されている場合(no)すべてがAJAXで、選択の順序に関係なく。

私は自分自身を明確にしました。 必要に応じてコードを読み込むことができます。

ありがとうございます。 バスコ

これは私がこれまで持っているものです。

Ajax.php

<?php 
db connection variables 


if(!isset($_GET['id'])){ 
    echo json_encode(array('success' => false, 'price_1' => '', 'message' => 'no id given')); 
    exit; 
} 

try { 
    $conn = new PDO("mysql:host=$servername;dbname=test", $username, $password); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} catch (PDOException $e) { 
    trigger_error("Connection failed: " . $e->getMessage()); 
    echo json_encode(array('success' => false, 'price_1' => '', 'message' => 'shit happened' . $e->getMessage())); 
    exit; 
} 

$stmt = $conn->prepare("SELECT price_1 FROM table WHERE id = ?"); 
$stmt->execute(array($_GET['id'])); 
$result = $stmt->fetch(PDO::FETCH_ASSOC); 

if($result === false){ 
    trigger_error('Query failed: ' . $conn->errorInfo()); 
    echo json_encode(array('success' => false, 'price_1' => '', 'message' => 'shit happened')); 
    exit; 
} else { 
    echo json_encode(array('success' => true, 'price_1' => $result['price_1'], 'message' => '')); 
    exit; 
} 

のindex.php

<?php 
Connection Variables 
try { 
    $conn = new PDO("mysql:host=$servername;dbname=test;charset=UTF8", $username, $password); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} catch (PDOException $e) { 
    trigger_error("Connection failed: " . $e->getMessage()); 
} 
$query = "SELECT `id`, `items`, `price_1` FROM `table`"; 
$rows = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC); 
?> 
<!DOCTYPE html> 
<html> 
    <head> 

     <script> 
      function getPrice(id){ 
       var xmlhttp = new XMLHttpRequest(); 
       xmlhttp.onreadystatechange = function() { 
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
         var jsonObj = JSON.parse(xmlhttp.responseText); 
         if(jsonObj.success === true){ 
          document.getElementById("price_1").value = jsonObj.price_1; 
         }else{ 
          document.getElementById("price_1").innerHTML = jsonObj.message; 
         } 
        } 
       }; 
       xmlhttp.open("GET", "ajax.php?id=" + id, true); 
       xmlhttp.send(); 
      } 
     </script> 
    </head> 
<body> 



<div> 

<h3>GET A QUOTE</h3> 



    Item: 
    <br> 
    <select name="price" id="priceSelect" onchange="getPrice(this.value)"> 
     <option>Please select:</option> 
    <?php foreach ($rows as $row): ?> 
     <option value="<?= $row['id'] ?>"><?= $row['items'] ?></option> 
    <?php endforeach; ?> 
    </select> 
    <br> 

    size: 
    <br> 
<select name="price" id="sizeselectSelect" onchange="sizePrice(this.value)"> 
     <option>Please select:</option> 
     <option value="1">size1</option> 
     <option value="2">size2</option> 
     <option value="3">size3</option> 
    </select> 

<br> 
     double: 
     <br> 
     <select name="bouble" id="doubleprice" onchange="lastprice(this.value)"> 
     <option>Please select:</option> 
     <option value="yes">Yes</option> 
     <option value="no">No</option> 
    </select> 
<br> 
<br> 
Total price: 

    <input type="text" name="price_1[]" value="" id="price_1">&euro; 
    <p id="error"></p> 


</body> 
</html> 
+0

コードスニペットを使ってこれまでに行ったことを、今のところ理解できないように達成しようとしていることを理解しやすくすることができたら、 – kabirbaidhya

答えて

0

私が座るにはAJAXを簡素化するjQueryのを使用します。

データがそれほど大きくない場合は、ページロード時にajaxリクエストを行い(ユーザー待ち時間の息子のajaxコールを防ぐため)、結果をjavascriptグローバル/オブジェクトに格納します。

ページがまったく更新されないように意図されていて、データが「生きている」ためのものであれば、待ち時間がかかってしまうかもしれませんが、ユーザーがオプションを選択したときにajax呼び出しを開始するだけです。

あなたはこのよう同様の構造を使用することができます。

//bind event of select changing to a funciton that fires off the ajax 
//the below avoids having to attach/unattach evenmt handlers on any dynamic elements 
var body = jQuery("body"); 
body.on("change","#selectID",updatePriceFunction); 

function updatePriceFunction() { 
    loader.show();//unhide the loading animation 
    var optionChosen = jQuery("#selectID").find("option:selected").val();//this assumes the options have values that are identifies for that option to be sent to the ajaxEndpoint 
     var payload = {selectedOption: optionChosen, otherData: otherValueNeeded}; //makes a javascript object with values to be sent to fetch the price 
     jQuery.ajax({ 
      type: "POST", 
      url: urlToAjaxEndpoint,//string 
      data: payload, 
      dataType: "json", 
      traditional: true, 
      success: getDataSuccess, 
      error: ajaxErrorHandling, 
      complete: function() {loader.hide();}//always hide the loading animation, even if ajax fails 
     }); 

     //methods seperated (not inline in the above ajax call) as to allow for reuse 

     function getDataSuccess(data){//data is the response form the server, parsed using jQuery JSON if the ajaxEndpoint server said the response type was JSON 
     if(data.result == true) { 
      //find the table area you wnat to update, and use the new value 
      //data.result ..... 
     } else { 
      //server returned value indicating operation was successful, such as if the combo was invalid or not, etc 
      //data.message .... 
     } 
     } 

     function ajaxErrorHandling(jqXHR, textStatus, errorThrown){//jqXHR is the jquery xml html request object 
      //ajax error connecting to endpoint/exception on response parsing 
      var details = JSON.stringify(jqXHR, null, 4); 
      console.error("Exception: "+errorThrown+" - Status: "+textStatus + " - XMLHTTPRequest:" + details); 
      showAlertMessage("An error occurred"); 
     } 
} 

//this assumes the server returns a json object of the form: 
//[ 
// error: true/false, 
// message: "", 
// result: object 
//] 

//whatever the endpoint uses, you'll likely need to parse the payload object, and then create a json response 
//be careful of special characters on the endpoint, as they can be "escaped" in the raw json and will throw a parse exception 

これは、あなたが正しい道を始めるために十分でなければなりません。 PS:jQueryは必要ではありませんが、それはずっと簡単です。

関連する問題