Dilan
Dilan

Reputation: 91

PHP AJAX update MySql query onChange from dropdown (filtering)

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.

Upvotes: 0

Views: 6329

Answers (4)

Martin
Martin

Reputation: 2414

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.

Upvotes: 0

Squalo
Squalo

Reputation: 149

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>

Upvotes: 0

Virb
Virb

Reputation: 1578

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>';

Upvotes: 1

Hammurabi
Hammurabi

Reputation: 305

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);
        }
    });
});

Upvotes: 1

Related Questions