0

I'm having problems with updating the products page on dropdown change using PHP in combination with Ajax. Right now it's not updating the query when I select an item from the dropdown menu. The query itself is working fine.

What I want is: when a user selects a different option from any of multiple dropdown menus, the query is updated by means of an Ajax POST request. Thus the results get filtered by the selection of the dropdown.

The HTML:

<select id="Gender">
    <option value="" disabled selected>--Geslacht--</option>
    <option value="1">Man</option>
    <option value="2">Vrouw</option>
    <option value="3">Beide</option>
</select>

The PHP MySQL query to select the data:

$statements = '';
    if (isset($_POST['GenderID'])) {
         $gender_query = $_POST['GenderID'];
        $statements .= " AND `product`.`gender_id` = '$gender_query' "; //condition for each property
    }


    $query = "SELECT    `product`.`product_name` AS pname, 
                        `product`.`product_img` AS pimg,
                        `brand`.`brand_name` AS bname
            FROM
                        `product`                                           
            INNER JOIN
                        `brand`
            ON 
                        (`product`.`brand_id`=`brand`.`brand_id`)   
            WHERE 
                        `product`.`active` = '1' $statements";

  $result2 = $conn->query($query);  

                    if ($result2->num_rows > 0) {
                    // output data of each row
                       while($row = $result2->fetch_assoc()) 
                        {                       
                            echo'
                            <div class="col-lg-4">
                                <div class="card">

                                   <div class="view overlay">

                                    <a href="#">
                                        <img src="products/',$row["pimg"],'" class="img-fluid">
                                    </a>
                                        </div>

                                        <div class="card-body">
                                            <h4 class="card-title">',$row["bname"],'</h4>
                                            <p class="card-text">',$row["pname"],'</p>
                                            <a href="#" class="btn btn-outline-success my-2 my-sm-0">Button</a>
                                        </div>

                                    </div>
                                    </div>';
                                }
                            }

The JS Jquery/Ajax:

$(document).ready(function(){
    $("#Gender").change(function () {
        var gender = $("#Gender").val();
        jQuery.ajax({
            type: "POST",
            data:  {GenderID: gender},
            success: function(data){ 
                if(data.success == true){ 
                   alert('success'); 
                }
            }               
        });
    });
});

It's probably the smallest mistake that I'm making. Any help is much appreciated.

UPDATE

I've added the code of what executes the Mysql query.

6
  • 1
    Warning! You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Specially since you're not escaping the user inputs at all! Commented Apr 20, 2018 at 12:54
  • what do you do with $query after you create it? Commented Apr 20, 2018 at 12:56
  • I'm not a JS guy so I can't help you in that area, but for me the question's unclear in regards to the php/mysql and it's hard to say if you executed the query or not and if you're checking for errors for those, including looking at the developer console. Commented Apr 20, 2018 at 12:56
  • Thank you for your comments. I'm aware the SQL injection is possible at this moment. However, I'm still fully working on the project and this is something that will be added. There is no error or something at the moment. Just nothing happens when you select any option from the dropdown menu.
    – Dilan
    Commented Apr 20, 2018 at 12:58
  • Try your code by removing single quotes around $gender_query in $statement. Single quotes will not get interpreted by compiler. May be that is the reason you are not getting data. Commented Apr 25, 2018 at 6:21

4 Answers 4

1

I think you are going wrong here.

A small mistake of '' in GenderID. And you are not passing url though.

$(document).ready(function(){
    $("#Gender").change(function () {
        var gender = $("#Gender").val();
        jQuery.ajax({
            url: "www.some_url.com"    // Send the data with your url.
            type: "POST",
            data:  {'GenderID': gender},     // Here you have written as {GenderID: gender} , not {'GenderID': gender}
            success: function(data){ 
                if(data.success == true){ 
                   alert('success'); 
                }
            }               
        });
    });
});

Also you have change in for . not as , as below.

echo' <div class="col-lg-4">
          <div class="card">
                 <div class="view overlay">
                    <a href="#">
                      <img src="products/'.$row["pimg"].'" class="img-fluid">
                    </a>
                 </div>
                 <div class="card-body">
                 <h4 class="card-title">'.$row["bname"].'</h4>
                 <p class="card-text">'.$row["pname"].'</p>
                 <a href="#" class="btn btn-outline-success my-2 my-sm-0">Button</a>
           </div>
       </div>
  </div>';
2
  • Thank you for your reply. I've changed the code to your suggestion. Unfortunately the result is still the same as it was. Selecting any value from the dropdown doesn't change the products that are being displayed. I think I'm also not seeing the 'success' alert. Any other suggestions?
    – Dilan
    Commented Apr 20, 2018 at 13:09
  • You don't need it to be data: { 'variable' : OtherVariable }, for it to work. The post variable should work fine without single quotes around it.
    – Martin
    Commented May 29, 2018 at 11:29
1

You dont call a script (missing the url argument).

$("button").click(function(){
    $.ajax({
        url: "demo_test.txt", 
        success: function(result){
        $("#div1").html(result);
    }});
});

edit: errorhandling can show you what is wrong

$("button").click(function(){
    $.ajax({
        url: "demo_test.txt", 
        success: function(result){
        $("#div1").html(result);
            },
        error: function (error) {
            console.log(error);
        }
    });
});
2
  • Thank you for the reply. I'm on purposely not calling a script because I want to pass the value of the dropdown on the same page. I've found how to do this here: stackoverflow.com/questions/7561569/…
    – Dilan
    Commented Apr 20, 2018 at 13:14
  • add some error handling ... and dont know it is posible witheout url:
    – Hammurabi
    Commented Apr 20, 2018 at 13:21
0

You can do in that way!

<?php
if(isset($_POST['gender'])) {$variable = $_POST['gender'];} else {$variable=0;}
echo $variable;?>

<div id="result">

<form action="" method="POST" id="form">
<select id="gender" name="gender">
    <option value="" disabled selected>--Geslacht--</option>
    <option value="1">Man</option>
    <option value="2">Vrouw</option>
    <option value="3">Beide</option>
</select>
<button type="submit" onClick="post()">Submit</button>
</form>
</div>

<script language="JavaScript" type="text/javascript">
function post() {
var param = '&gender='+gender;
$.ajax({
url : 'pagename.php',
type : 'POST',
data : param,
dataType : 'html'
}).done(function(html) {$('#result').html(html)}) ;
}
</script>
0

Are you getting the correct post data? What does your post variable actually contain after you parse it to the other file via AJAX?

A thing that caught my eye, which could be a mistake, is the way you fetch the value of your <select> . As far as I know, you're supposed to tell it to get the selected value of the select.

var gender = $("#Gender").val();

needs to be

var gender = $("select#Gender option:selected").val();

In this way, you're telling the jquery variable what value to fetch.

If you still have issues after this, let me know, and I'll edit my answer if I find any other errors.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.