Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Rodrigo Vazquez
Rodrigo Vazquez
5,502 Points

Problems when trying to append to a DIV

Hello guys.. Im not sure if I am doing the correct method to load a webpage if users are logged in. Im using PHP + JQuery/Javascript My code is the following:

<div id="ajax_load"></div>

<? require_once("models/config.php"); if(isUserLoggedIn()){ echo '<script> $(document).ready(function () { $.get("ajax_load.php",function(data){ $("#ajax_load").html(data); alert("HTML being Loaded from Get Request: " + data); }); }); </script>'; } else { header("Location: login.php"); } ?>

Is this a good practice? The alert is loading with the HTML, also the Console log is telling me the request was succesfull (200). Not sure why the HTML is not appending to the div id="ajax_load" Am I doing something wrong? Is there a better method instead of this to load a page if users are logged in?

Thanks!

Rodrigo Vazquez
Rodrigo Vazquez
5,502 Points

I also used this:

<script>$('#ajax_load').load('/ajax_load.php');</script>

But its not loading the HTML data into the #ajax_load div

1 Answer

Since you're already detecting whether the user is logged in via PHP, why not generate the HTML in the PHP and return that instead of returning JS that will require another network call?

<? require_once("models/config.php"); if(isUserLoggedIn()){ include('/ajax_load.php'); } else { header("Location: login.php"); } ?>

Rodrigo Vazquez
Rodrigo Vazquez
5,502 Points

You are totally right. I just wanted to know how that worked as an excersice to put in practice when I start doing functions to load PHP pages from the menu. Whats the common use to load PHP pages that requires to process information? Is it: $('#id').load('page.php'); The best option to load? Do I need to add a slash? $('#id').load('/page.php'); or what about the directory. Just making clear this.