Ducky
Ducky

Reputation: 409

can't load php file with jquery and access variable outside the file

If I load my php file (Home.php) via Jquery, I can't seem to be able to access $var in my Home.php file. It loads succesfuly but I get this "undefined" error:

( ! ) Notice: Undefined variable: var in /media/sf_sandbox/linksup/view/Home.php

I have done this in this exact same order. I declare the variable:

index.php

<?php
    $var = "bar";
?>

I load the file Home.php with .load():

index.php

<div id="ContentContainer">
    <script>        
        $( "#ContentContainer" ).load( "view/Home.php" );
    </script>
</div>

I then try to get the value of $var in Home.php:

Home.php

<div class="row">
        <div class="col-md-12">
            <h2>Home</h2>
            <?php echo $var?>
        </div>
</div>

Upvotes: 3

Views: 485

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Why you are using jquery for that purpose. PHP include_once() will do that easily.

In Home.php do like below:-

<?php include_once('index.php');?>
<div class="row">
        <div class="col-md-12">
            <h2>Home</h2>
            <?php echo $var?>
        </div>
</div>

Upvotes: 1

Related Questions