Ligthers Ligthers - 3 days ago 5
Ajax Question

change query based on textbox change using ajax and php

I've been trying to change a query using php with ajax. Here's how it goes


  1. I have a dropdown that when changed it will then copy the selected data to a textbox which I achieved using javascript like so.

    $(document).ready(function () {
    $("#animaloption").change(function () {
    $('#animalfilter').val($("#animaloption").val());
    });
    });



And then


  1. I need to check if input textbox with id of animalfilter is changed and then query it using ajax which I did not know if this one is correct since I cannot retrieve the return

    $(document).ready(function () {
    $("#animaloption").change(function () {
    $('#animalfilter').val($("#animaloption").val());
    var animal= $('#animalfilter').val($("#animaloption").val());
    $.ajax({
    url: "ajax/test.php",
    type: "post",
    data: animal,
    success: function (response) {
    $("#kind").html(response);
    }
    });
    });
    });



an input with id = kind does not show anything.

In my test.php

<?php
$a = "SUCCESS";
return $a;
?>


Kindly help guys.

Thanks.

Answer

You have a couple issues going on here, I will note the areas of concern:

jQuery:

$(document).ready(function() {
    // Not necessary, but better to use .on() here
    $("#animaloption").on('change',function() {
        // Use $(this) instead, grabs the selected value. No sense in
        // capturing the same event value when you have it in this event already
        var animal = $(this).val();
        // Assign value here to field
        $('#animalfilter').val(animal);
        // Start ajax
        $.ajax({
            // Make sure this is the correct path
            url: "ajax/test.php",
            type: "post",
            data: animal,
            success: function(response) {
                $("#kind").html(response);
            }
        });
    });
});

/ajax/test.php

<?php
$a = "SUCCESS";
# You have to echo, not return
echo $a;
# Try print_r() for sure-fire results testing
print_r($_POST);

If these changes don't fix it, seeing your form html will be necessary.

Comments