skip to Main Content

I have an old Laravel project (version 8). In it, I have Blade templates with code like the following.

<div id='product-container'>
  @if(home_base_price($product) != home_discounted_base_price($product))
    <del class="fw-600 opacity-50 mr-1">
      {{ home_base_price($product) }}
    </del>
  @endif
  {{ show_percentage($product_price) }} 
  {{ $product->product_image }}
  {{ $product->getTranslation('name') }}
  // These syntaxes are written along with other HTML/CSS code.
</div>
<button id="load_more_button" class="btn btn-primary">Show more</button>

I’m fetching product data from an AJAX request in JSON format with a jQuery script and trying to append the HTML content as new products when clicking the show more button (on click pagination).

<script>
$(document).ready(function() {
    var start = 12; 
    $('#load_more_button').click(function() {
        $.ajax({
            url: "https://example.com/load-more-products",
            method: "GET",
            data: {
                start: start
            },
            dataType: "json",
            beforeSend: function() {
                $('#load_more_button').html('Loading...');
                $('#load_more_button').attr('disabled', true);
            },
            success: function(data) {
                if (data.data.length > 0) {
                    var html = '';
                    for (var i = 0; i < data.data.length; i++) {
                        var product = data.data[i];
                        html += '<div id="product-container">' +
                        <!-- I want to write the Blade syntaxes that have been used in the Blade template, here -->            
                        '</div>';
                    }
                    // rest code

</script>

How do I write the Blade syntaxes inside the jQuery script?

2

Answers


  1. Blade syntax only works in a PHP file with a .blade.php extension. So, you have two options.

    1. Make the script a .blade.php file and use @include to call it into your blade file.

    2. Have a <script></script> tag in your blade file. Define the variables there and call them in the JS/jQuery script. An example of this is given below

    <script>
      var var1 = '{{ $variable1 }}';
      var var2 = '{{ $variable1 }}';
    </script>
    

    If the variables are not detected in the script, remove the var keyword and try again.

    Login or Signup to reply.
  2. you could use
    <script> var myvariable = "{{$phpVar}} </script>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search