Could not access class object in php file downloaded via ajax

I am having a little problem with below, I am trying to study some future projects and need a hand.

Here is the setup:

  • I have a user class in php in the models directory.
  • I have a home.php file in the root directory.
  • I have included the model for the custom class in the home.php file and I can access it simply.
  • I have a profile.php file that I would like to upload via ajax to the home.php file.
  • I can download the profile.php file very well, however, the problem is that the information on this page, which is just called via <?php echo $user->first_name; ?> <?php echo $user->first_name; ?> is not displayed when I load the page via ajax. However, if I load the page usually without ajax, it displays just fine.

What I have tried so far:

  • I tried to include the user class in the profile page, but it gives me an error that it is already included.
  • I would prefer not to put this in a session variable, as I would like to access this class here.
  • I also need to have access to the user class on other screens, so I included it in the home.php file.

Any help would be greatly appreciated since I am pretty new to php and ajax.

thanks

Here is the code I'm working with.

home.php

 //Here we include are models that we need access to. include 'apps/user/model/user.php'; $my_user = new User(); global $user; $user = $my_user->getUserById($_SESSION['loggedin_user_id']); 

profile.php

 <input type="text" value="<?php echo $user->username; ?>" class="input-xlarge"> 

javascript to load form via ajax

 $.ajax({ url: 'apps/user/view/profile.php', success: function(data){ if(data != null) $("#content").html(data); } }); 

I also get the following error while viewing the console.

[01-Jun-2013 10:38:03] PHP Note: Undefined variable: user in / Users / btackett 1377 / development / Test / Base / apps / user / view / profile.php on line 23

+4
source share
1 answer

Have you tried using require_once instead of include ? I would try using the user class on both the home page and the profile page.

For your reference, PHP has four functions for including files:

  • include - Blindly include the requested file, not considering whether it was already included. Alerts you if a file is not found.
  • include_once - Make sure the file is included only once. Also warns you if the file is not found.
  • require - Like include , but causes a fatal error if the requested file is not found.
  • require_once - Like include_once , but leads to a fatal error if the file is not found.
0
source

Source: https://habr.com/ru/post/1483945/


All Articles