send selected dropdown value to another PHP page

user :

I do not use submit button

I want the selected value from the user sent to the test1.php page, but when the user selects an option nothing happen in the page, and the value is not sent to the test1.php page

Is there any mistake in my code, or did I miss something ?

test2.php


<?php include_once 'database.php';

?>


<head>



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>



    <script>


        $(function() {
            $('.category').change(function() {
                var category = $('.category option:selected').val();
                alert('category changed to ' + category);
                $.ajax({
                    method: "POST",
                    url: "test1.php",
                    data: {
                        category1: $(this).val()
                    },
                    success: function(data) {
                        console.log(data);
                    }
                });
            });
        });



    </script>






</head>
         <p> Filter By Category</p>
    <select id="category" class="category">
                                <?php
                                $query = mysqli_query($conn,"select * from category ");
                                while($category = mysqli_fetch_array($query)) {
                                    echo "<option value='" . $category['cat_name'] . "'>" . $category['cat_name'] . "</option> ";
                                }
                                ?>
                            </select>





test1.php

<?php
include_once 'database.php';

if (isset($_POST['category1'])) {
    $category = $_POST['category1'];
    echo $category;
}
?>
Artiko :

is that all your file ? did you forget to include jquery ?

I just did the same script as yours but in html, and console said $ not found, after add jquery that's working

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
$(function() {
$('.category').change(function() {
$.ajax({
method: "POST",
url: "https://webhook.site/2d574d22-5570-46f2-b5bd-343d715adff4",
data: {
category1: $(this).val()
},
success: function(data){
console.log(data);
}
});
});
});
</script>
    </head>
    <body>
        <p> Filter By Category</p>
<select id="category" class="category">
    <option value='1'>One</option>
    <option value='2'>two</option>
</select>
    </body>
</html>

here is the webhook to check your request, it is like test1.php but just for debugging purpose https://webhook.site/#!/2d574d22-5570-46f2-b5bd-343d715adff4/e3406220-f58e-45be-a4ef-13d8d3e0b0d3/1

here are some advices:

  • inspect your page using developer tools, maybe there are some errors
  • check with console.log .val()

hope this help

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401730&siteId=1