Search code examples
javascriptphpjsonajaxeasyautocomplete

Storing JSON result from ajax request to a javascript variable for Easyautocomplete


I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.

I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.

Here is what I have so far:

$('#customerid').on('change',function() {
    var products2 = {
          url: function(phrase) {
            return "database/FetchCustomerProducts.php";
        },  
        ajaxSettings: {
            dataType: "json",
            method: "POST",
            data: {
                dataType: "json"
            }
        },
        preparePostData: function(data) {
            data.phrase = $("#customerid").val();
            return data;
          },
        getValue: "name",
        list: {
            onSelectItemEvent: function() {
                var value = $("#productname").getSelectedItemData().id;
                $("#productid").val(value).trigger("change");
            },
            match: {
              enabled: true
            }
        }
    };

$("#productname").easyAutocomplete(products2);
});

Contents of FetchCustomerProducts.php:

if(!empty($_POST["customerid"])){

    $products = $app['database']->Select('products', 'customerid', $_POST['customerid']);

    echo json_encode(['data' => $products]);

}

However it's not working. The code is based on the 'Ajax POST' example found on this page.


Solution

  • you can using element select category add is class "check_catogory" after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode

    $("#customerid").change(function(){
        var id = $(this).val();
        if(id!=""){
            $.ajax({
                url:"database/FetchCustomerProducts.php",
                type:"POST",
                data:{id:id},
                dataType: "json",
                cache:false,
                success:function(result){
                     var options = {
                        data:result,
                        getValue: "name",
                        list: {
    
                            onSelectItemEvent: function() {
                                var value = $("#productname").getSelectedItemData().id;
                                $("#productid").val(value).trigger("change");
                            },
    
                            match: {
    
                              enabled: true
    
                            }
    
                        }
                    };
                    $("#productname").easyAutocomplete(options);
    
                }
            })
        }
    });