Gad
Gad

Reputation: 42306

What's the best way to include html through an ajax echo command?

I am currently building a small website where the content of the main div is being filled through an Ajax call. I basically have a php script that returns the content like this:

(simplified php script...)


if(isset($_POST["id_tuto"])){
  PrintHtml($_POST["id_tuto"]);
}

function PrintHtml($id)
{
  switch($id)
  {
    case [...]:
      echo "THIS IS MY HTML CONTENT";
    break;
    [...]
  }
}

The web page then gets the text from that echo command and replaces the inner html of the content div.

My question is this : What is the best way to echo that html content? there is a lot of content each time since it's a step by step tutorial. Each string will be about 50-80 lines of HTML code. Is there a way to put that html content in a separate html file and echo that file or...?

Thanks a lot!!

Upvotes: 1

Views: 1280

Answers (4)

defrex
defrex

Reputation: 16435

You could do it like so:

<?php
    function PrintHtml($id) {
      switch($id) {
          case [...]:
?>
      <h1>Tut page 1</h1>
      <p>this is html content.</p>
<?php
      break;
      [...]
    }
  }
?>

Or perhaps:

<?php
  function PrintHtml($id) {
     switch($id) {
      case [...]:
      include 'section1.php';
      break;
      [...]
    }
  }
?>

Upvotes: 2

Clutch
Clutch

Reputation: 7600

Try separating your data (Human readable text) from your formatting (HTML) I suspect that 50 - 80 lines of HTML could be separated. You could create several HTML templates and then add your data into the template as needed. I would definitely use Prototype or some JavaScript library to handle receiving the JSON formated data on the client side. You can have your data in flat files but I think a database would be faster and less prone to errors. MVC pattern would definitely help here.

Upvotes: 0

pkaeding
pkaeding

Reputation: 37643

You should use a templating system, such as Smarty. This will allow you to keep your html separate from your code logic.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

You just do it the way you'd normally generate an HTML page, except it is not wrapped in HTML HEAD or BODY tags. It's just the HTML fragment that will be added to your page.

Everything you "echo" becomes part of the output. You can do it is pieces or all on one go, it doesn't matter because it call gets sent to the browser as "the response" as one chunk anyways.

Upvotes: 0

Related Questions