Bodil132 Bodil132 - 1 year ago 46
Ajax Question

How do I send Select value to PHP with Jquery Ajax?

First of all, thank you for taking a look at my question.

Also, I looked everywhere on Stackoverflow for a solution but I just can't get this to work.

So here's the problem, I need to get the value of a select option that is in file

and send it to
so I can fetch the appropriate data from the database. Basically when I select another option I want the page to load the appropriate data.

Here's the Ajax (job.php)

$( document ).ready(function() {
var workselected = $('.work-select').val();
method: "POST",
url: "php/portfolio.php",
data: {workselected1: workselected},
success: function(data){

Heres the Select tag I'm trying to get the value from (job.php)

<select id="select-work" class="work-select">
<option class="work-option" value="fw">Option 1</option>
<option class="work-option" value="bw">Option 2</option>
<option class="work-option" value="lp">Option 3</option>
<option class="work-option" value="et">Option 4</option>
<option class="work-option" value="wa">Option 5</option>

Here's the PHP that handles DB interaction (portfolio.php)


if (isset($_POST['workselected1'])) {
$workselected = $_POST['workselected1'];

$query = mysqli_query($conn, "SELECT * FROM sometable WHERE project_category=`workselected`");
$rowCount = mysqli_num_rows($query);

} else echo "NOT WORKING";

$i = 0;
echo '<div class="row rowcontrol">';

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

echo '<div class="col-md-4 letmesee"><div class="work-content-container">'; ?>
<a href="#"><img src="img/project/<?php echo $row['thumbnail_ref'] ?>" class="work-thumbnail"></a>
<span class="caption slide-caption">
<h5><?php echo $row['project_name']; ?></h5>
<p><b>Project: </b><?php echo $row['project_type'];?></p>
<p><b>Check: </b><a href="<?php echo $row["project_url"];?>" class="nav-link"><?php echo $row["project_url"]; ?></a></p>
<?php echo '</div></div>'; ?>

if ($i%3 == 0) echo '</div><div class="row">';

} ?>

<?php } ?>

I'm not getting anything from this code, the data is not passing to the other file, I think I'm missing something; Maybe I need to add a click event somewhere in there? please help!

Answer Source

You say Basically when I select another option I want the page to load the appropriate data. So you have to register a change listener then. Otherwise you only do it once at page load.

$(function() {
    $('.work-select').change(function() {
            method: "POST",
            url: "php/portfolio.php",
            data: {
                workselected1: $(this).val()
            success: function(data){

If you want an initial loading too, you can wrap the ajax within a function, or trigger it once manually.