1

I have a select on which I want it to execute a query onchange.

(I want to get certain price for the product, depending on the size selected)

The problem is that I'm new to Ajax, and I don't know how to send multiple data. The first variable is the value from the select, and the second var, is the ID from the page someone is visiting.

I need to send to the "getprice.php" page the variables $i, which is $_GET["hidden_id_product"] and $q, which is the value from the onchange select.

I'm stuck here, this is my first post, I couldn't find a response for this, hope someone could help me out.

Select code: (product.php)

<select name="size" id="size" class="form-control" onchange="sizeSelected(this.value)">
<?php 
    $size_query = "SELECT * FROM sizes WHERE id_product=".$_GET["hidden_id_product"];
    $size_result= mysqli_query($connection, $size_query);
    if($fetch = mysqli_fetch_array($size_result)){
       echo "<option selected value='0' disabled> - SELECT A SIZE - </option>";
       if($fetch["seven"] > 0){
            echo "<option value='7' > 7us </option>";
       }else{
            // do nothing                               
       }
       if($fetch["sevenhalf"] > 0){
            echo "<option value='7.5'> 7.5us </option>";
       }else{
            // do nothing                               
       }
       // and so on... 
    }else{
        echo "<option value='0'>SOLD OUT</option>";
    }
?>
</select>

Script Used: (product.php)

<script>
    function sizeSelected(str) {
    var div = document.getElementById("id_product");
    var str2 = div.textContent;
    if (str == "") {
        document.getElementById("price").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("price").innerHTML = this.responseText;
            }
        };

        xmlhttp.open("GET","getprice.php?q="+str+"&i="+str2,true);
        xmlhttp.send();
    }
}
</script>

Get price code: (getprice.php)

<?php
include("connection.php");

$q = intval($_GET['q']);
$i = $_GET['i'];

if($q = 7){
    $qt = "seven";
}elseif($q = 7.5){
    $qt = "sevenhalf";
}elseif($q = 8){
    $qt = "eight";
}elseif($q = 8.5){
    $qt = "eighthalf";
}elseif($q = 9){
    $qt = "nine";
}elseif($q = 9.5){
    $qt = "ninehalf";
}elseif($q = 10){
    $qt = "ten";
}elseif($q = 10.5){
    $qt = "tenhalf";
}elseif($q = 11){
    $qt = "eleven";
}elseif($q = 11.5){
    $qt = "elevenhalf";
}elseif($q = 12){
    $qt = "twelve";
}elseif($q = 13){
    $qt = "thirteen";
}

$sql="SELECT ".$qt." FROM prices WHERE id_product = ".$i;
$result = mysqli_query($connection,$sql);

while($row = mysqli_fetch_array($result)) {
    echo $row[$qt];
}
?>

The full page:

<div>
    <span><h2><?php echo $row["name"];?></h2></span>
    <hr>
    <span><h3>"<?php echo $row["nickname"];?>"</h3></span>
    <hr>
    <span>
        <div id="id_product" style="display: none;">
            <?php 
            $id = $_GET["hidden_id_product"];
            echo htmlspecialchars($id);
            ?>
        </div> 
        <h4>
            <?php echo $row["id_product"]; ?>
            | <?php echo $row["brand"]; ?> 
            | <?php echo $row["year"] ?>    
        </h4>
    </span><br>
    <span>
        <select name="size" id="size" class="form-control" onchange="sizeSelected(this.value)">
        <?php 
            $size_query = "SELECT * FROM sizes WHERE id_product=".$_GET["hidden_id_product"];
            $size_result= mysqli_query($connection, $size_query);
            if($fetch = mysqli_fetch_array($size_result)){
                echo "<option selected value='0' disabled> - Seleccione una talla - </option>";

                if($fetch["seven"] > 0){
                    echo "<option value='7' > 7us </option>";
                }else{

                }
                if($fetch["sevenhalf"] > 0){
                    echo "<option value='7.5'> 7.5us </option>";
                }else{

                }
            }else{
                echo "<option value='0'>SOLD OUT</option>";
            }
        ?>
        </select><br>
    </span>
    <div id="price"></div>

</div>
Duncanista
  • 83
  • 1
  • 8
  • First thing I see is missing quotes around `$i` on the SQL query. It should be `$sql="SELECT ".$qt." FROM prices WHERE id_product = '".$i."'";` -- Is there any PHP error or console error? – Louys Patrice Bessette Jun 29 '17 at 19:38
  • The `$i` is a number, it doesn't need the quotes around it – Duncanista Jun 29 '17 at 19:46
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Jun 29 '17 at 19:48
  • Thank you @AlexHowansky I will fix all the queries after I solve this problem!! – Duncanista Jun 29 '17 at 19:52
  • *«The $i is a number...»* Really? I see: `var str2 = div.textContent;` and `&i="+str2`... But that's your code... – Louys Patrice Bessette Jun 29 '17 at 19:56
  • @LouysPatriceBessette I just used the `str2` to test, it's not a string, I really don't know how to pass a PHP var to JS, that's the main question. I just used something from a post I found here. That's why I'm struggling – Duncanista Jun 29 '17 at 19:58

1 Answers1

1

«I really don't know how to pass a PHP var to JS, that's the main question.»

I don't see any attempt to pass a PHP value directly to JS.
But it would theorically be to like this:

<?php
$myPHPvariable = 34;
?>
<script>
var myJSvariable = <?php echo myPHPvariable; ?>;
console.log(myJSvariable);
</script>

Okay, I now assume you correctly build the select elements... And that you need to pass the selected option value and text to get the item price.

So say your produced HTML looks like this:

<select name="size" id="size" class="form-control">
  <option selected value='0' disabled> - SELECT A SIZE - </option>
  <option value='7' > 7us </option>
  <option value='7.5'> 7.5us </option>
  <option value='0'>SOLD OUT</option>
</select>

You tagged your question with jQuery...
Since I'm more used to jQuery Ajax than XMLHttpRequest, here is the way I would do it to send the selected value and the selected option text:

First, remove that inline event handler onchange="sizeSelected(this.value)" from the select.
And use a jQuery event handler.

// Change handler
$("#size").on("change",function(){

  var SelectedValue = parseFloat($(this).val());
  var SelectedText = $(this).find("option").eq( $(this)[0].selectedIndex ).text();
  console.log(SelectedValue+" - "+SelectedText);

  // Prepare the data to send.
  var data = {
    q:SelectedValue,
    i:SelectedText
  };

    $.ajax({
      url:"getprice.php",
      method:"post",
      data:data,
      cache:false,
      success:function(result){
        $("#price").html(result);  // Display the price in the "price" div.
      },
      error:function(request,status,error){
        console.log(error);  // Ajax error, if any, will be shown in console.
      }
    })
});

I suggest you to use the post method... So in your PHP, change $_GET to $_POST.

Here, q or SelectedValue is an integer and i or SelectedText is a string.

So you should have the price in the <div id="price"></div> after the request.
If there was a PHP error (not an ajax request error, which would be shown in console), it will be displayed there too.

Also add this in case there would be an SQL error in getprice.php, right after $result = mysqli_query($connection,$sql);:

if (!$result) {
   printf("Errormessage: %s\n", $mysqli->error);
}

In hope that will help.
;)

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • It do logs in the console the values, but it says it's deprecated: `jquery.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.` – Duncanista Jun 29 '17 at 22:29
  • Thank you so much, the problem I had was that I needed to add the full URL in the ajax request. Instead of `url:"getprice.php",` I replaced it for `url:"http://example-com/getprice.php",` – Duncanista Jun 29 '17 at 22:57