1

Laravel how o can use javascript variables from include file? I try this below example but variable not found..

includeFile.blade.php

<script>
    $(document).ready(function () {
        var myMar = "Hello world";
    });
</script>

default.blade.php

@include('layouts.includeFile')

<script>
    $(document).ready(function () {
        alert(myVar); //Here myVar is undefined
    });
</script>

2 Answers 2

3

myVar must be declared outside the function to be visible in another functions

includeFile.blade.php

<script>
    var myVar; // Create global variable
    $(document).ready(function () {
        myVar = "Hello world";
    });
</script>

default.blade.php

@include('layouts.includeFile')

<script>
    $(document).ready(function () {
        alert(myVar);
    });
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

It is because myMar is private in includeFile.blade.php. Try something like this

includeFile.blade.php

<script>
    $(document).ready(function () {
        var myMar = "Hello world";
        @yield('doc_ready')
    });
</script>

default.blade.php

@extends('includeFile')
@section('doc_ready')
    alert(myVar); //Here myVar is defined
@stop

Or just remove var

<script>
    $(document).ready(function () {
        myMar = "Hello world";
    });
</script>

And also you have typo in includeFile it is myMar and in default it is myVar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.