JL Griffin
JL Griffin

Reputation: 423

How To Change My code to Use AJAX

I have built a basic MVC Font Controller application. its built for the purpose of easy site editing, index. php is the only page that every js, and css document is loaded from, then the front controller brings the appropriate content file forward and puts it inside a specified div, and the correct document can be called by adding ?pagename to the end of the url(For Example: site.com/index.php?about-us) . It works well with no PHP errors, however i am now trying to build an audio player into the site and want it to be persistent across pages, so i am trying to edit this mvc code to use ajax instead so that the page is not reloaded to change content. Below is my code for the page.

index.php code snippet

<div id="mpane-in">
    <?php

       /** Display errors in production mode Only DO NOT un-comment unless testing **/
       //ini_set('display_errors', 1);

       // Load the routing controller
       require 'application/router.php';
    ?>
</div>

/application/router.php

  require 'load.php';
  require 'model.php';

  require 'controller.php';
  new Controller(); 

load.php

class Load {
  function view( $file_name, $data = null ) 
    {
      if( is_array($data) ) {
         extract($data);
    }
    include 'pages/' . $file_name;
  }
}

model.php

class Model {
   public function user_info()
   {
      // simulates real data
      return array(
         'first' => 'Target',
         'last'  => 'Not_Loaded'
      );
   }
}

controller.php

 class Controller {
   public $load;
   public $model;

   function __construct()
   {
      $this->load = new Load();
      $this->model = new Model();

      // determine what page you're on
      $this->home();
   }

   function home()
   {
       if ($_SERVER['QUERY_STRING'] === ""){
        $data = $this->model->user_info();
        $this->load->view('main.php' , $data);
       }
       else {
        $data = $this->model->user_info();
        $this->load->view($_SERVER['QUERY_STRING'] . '.php' , $data);
       }
   }
}

Any suggestions would be great! thanks!

Upvotes: 0

Views: 298

Answers (1)

sakhunzai
sakhunzai

Reputation: 14470

In an oversimplified manner you can use your existing code without changing anything e. g

 class Controller {
  .....

  //call this ajax function 
  function ajaxLogin(){
       $this->load->partialView($_SERVER['QUERY_STRING'] . '.php' , $data);
  }
}

You just need to use partial views to avoid loading <html><header></body> , in case of text/html response and for json and xml output you might need to send proper content-type headers before echoing the view stuff. In a dirty and quick way add little stuff to handle content-type and partialviews and you are done .

Upvotes: 1

Related Questions