简体   繁体   中英

How to declare variable in javascript code that is declared in another file?

So I am using Laravel 5.5, PHP 7.0

I have this at the bottom of my views file:

$("#myRange").ionRangeSlider({
    type: "double",
    grid: true,
    min: {{ $minPrice }},
    max: {{ $maxPrice}},
    @if(isset($returnData['Ranges']) && count($returnData['Ranges']) > 0)
        from: {{ $returnData['Ranges']['0'] }},
        to: {{ $returnData['Ranges']['1'] }}
    @else
        from: {{ $minPrice }},
        to: {{ $maxPrice}}
    @endif
});

The error is that $minPrice and $maxPrice are undeclared. BUT they are declared in my controllers file.

Here's the code in my controller file:

    $fees = array_unique($fees);
    $priceRanges = array();
    $minPrice = 0;
    $maxPrice = 0;
    if(count($fees) > 0){
        foreach ($fees as $key => $value) {
            $range = explode(' - ', $value);
            $priceRanges[] = $range['0'];
            $priceRanges[] = $range['1'];
        }
        $priceRanges = array_unique($priceRanges);
        $minPrice = (int) min($priceRanges);
        $maxPrice = (int) max($priceRanges);
    }

Anybody how how can I fix the javascript code in my views (front-end) file to declare the variable? I get this error on one specific page only which shows a list of items in my database. If I search for an item from the homepage and then see the search results page, there's no error. Only on the listings page.

In your Javascript, do this

   $("#myRange").ionRangeSlider({
    type: "double",
    grid: true,
    min: @if(isset($minPrice)) {{ $minPrice }} @else 0 @endif,
    max: @if(isset($maxPrice)) {{ $maxPrice }} @else 0 @endif,
    @if(isset($returnData['Ranges']) && count($returnData['Ranges']) > 0)
        from: {{ $returnData['Ranges']['0'] }},
        to: {{ $returnData['Ranges']['1'] }}
    @else
        from: @if(isset($minPrice)) {{ $minPrice }} @else 0 @endif,
        to: @if(isset($maxPrice)) {{ $maxPrice }} @else 0 @endif
    @endif
});

If the value exists, echo it out, or else echo 0

Declare it using good old spaghetti code:

<?php
$minPrice = 0;
$maxPrice = 0;
?>

They don't need to be exposed to JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM