Search code examples
phpsqlajaxget

Get variable $_GET with ajax


I'm trying to build an ajax live search.

index.php

<div class="form-group">
    <div class="input-group">
        <span class="input-group-addon">Search</span>
        <input type="text" name="search_text" id="search_text" class="form-control" />
    </div>
</div>
<div id="result"></div>

<script>
$(document).ready(function() {
    load_data();
    function load_data(query) {
        $.ajax({
            url:"new/new_fetch.php",
            method:"POST",
            data:{query:query},
            success:function(data) {
                $('#result').html(data);
            }
        });
     }
     $('#search_text').keyup(function() {
         var search = $(this).val();
         if(search != '') {
             load_data(search);
         } else {
             load_data();
         }
    });
});
</script>

new/new_fetch.php

$connect = mysqli_connect("localhost", "root", "root", "dbname");
if(isset($_POST["query"])) {
    $query = "SELECT * FROM subcategories WHERE category_parent = '".$_GET['category']."' ORDER BY subcategory";
}

But I have an Undefined index: category in new/new_fetch.php error.

My code works without WHERE operator.

How can I get $_GET['category'] using ajax POST method? thx


Solution

  • The error is because you never passed the category variable in the AJAX. What you need to do is something like below:

    $.ajax({
        url:"new/new_fetch.php",
        method:"GET",
        data:{
            query:query,
            category:"SOME_VALUE"
        },
        success:function(data) {
            $('#result').html(data);
        }
    });
    

    UPDATE

    If you want to accept both $_GET and $_POST I recommend you to use $_REQUEST it covers both get and post.