Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP variable as Javascript function parameters

I'm using Laravel and I have two php variable in my blade view like this:

$dropDown = $formDataValue['name']
$emptyDropDown = $formDataValue['name'];

And I create a Javascript function with two parameters in same blade view:

function autoFill (dropDown, emptyDropDown) {
    $("#" + dropDown ).change(function() { 

        $.ajax({
            type: "GET",
            url: "https://api.myjson.com/bins/bcnss",

            success: function(response){

                var dataLength = response.length;
                $("#" + dropDown).empty();
                $("#" + dropDown).append("<option value=''>Select</option>");
                for( var i = 0; i< dataLength; i++){
                    var id = response[i].id;
                    var name = response[i].name;
                    $("#" + dropDown).append("<option value='"+id+"'>" + name + " </option>");
                }
            }
        });
    });
}

Then I call this:

<?php echo "<script> autoFill(".$dropDown.", ".$emptyDropDown."); </script>"; ?>

Problem is they can pass the parameters to function! I check element in browser and I see when I call this function, it's have parameters. But in the script tag, there nothing!

enter image description here

How I can fix this?

Thank you very much!

like image 571
Tomato Avatar asked Nov 21 '25 10:11

Tomato


1 Answers

Seems like you forgot about quotes, when you are passing strings into function.

<script>
    $(document).ready(function () {
        autoFill('{{ $dropDown  }}', '{{ $emptyDropDown }}');
    });
</script>

You can do it this way, but you shouldn't, because Laravel Blade do it for you itself.

<?php echo "<script> autoFill('".$dropDown."', '".$emptyDropDown."'); </script>"; ?>
like image 81
Roman Meyer Avatar answered Nov 23 '25 23:11

Roman Meyer