MVC controller and ajax


#1

Hi I’m trying to learn the basic of MVC, at the moment I’m not using oop but just procedural, not using a framework and not using a router.

I need to submit a form using ajax and jquery, the problem is if I submit the form to the controller then ajax returns the whole page, how can i just return echo $output; to the ajax call? . I use the controller to render the views as well and this is the controller

// Load settings files
require_once($_SERVER["DOCUMENT_ROOT"].'/config/load.php');
// Start session
session_start();

// Switch the view 
switch ($_SESSION['km-user-session']['km-user-role']) {

    case KM_ADMIN_ROLE:

        ob_start(); 
        // Load header for admin
        include_once(KM_ROOT_PATH.'/km-views/km-admin/km-header.php');
        $km_header = ob_get_contents(); 
        ob_end_clean(); 

            // Check if api is active and show different sidebar
            if($_SESSION['km-user-session']['km-api-active'] == true){

                ob_start(); 
                include_once(KM_ROOT_PATH.'/km-views/km-admin/km-api/km-sidebar.php');
                $km_sidebar = ob_get_contents(); 
                ob_end_clean(); 

            }else{

                ob_start();
                include_once(KM_ROOT_PATH.'/km-views/km-admin/km-sidebar.php');
                $km_sidebar = ob_get_contents(); 
                ob_end_clean(); 

            }

        // Load admin api receipts view
		include_once(KM_ROOT_PATH.'/km-views/km-client/km-api/km-receipts.php');
        break;

    case KM_CLIENT_ROLE:

        ob_start(); 
        include_once(KM_ROOT_PATH.'/km-views/km-client/km-header.php');
        $km_header = ob_get_contents(); 
        ob_end_clean(); 

    		// Check if api is active and show different sidebar
        	if($_SESSION['km-user-session']['km-api-active'] == true){

        		ob_start(); 
				include_once(KM_ROOT_PATH.'/km-views/km-client/km-api/km-sidebar.php');
				$km_sidebar = ob_get_contents(); 
				ob_end_clean(); 

        	}else{

        		ob_start();
				include_once(KM_ROOT_PATH.'/km-views/km-client/km-sidebar.php');
				$km_sidebar = ob_get_contents(); 
				ob_end_clean(); 

        	}


                if ($_SERVER["REQUEST_METHOD"] == "POST") {

            $startDate = $_POST['startDate'];
            $endDate = $_POST['endDate'];
            $clientCode = $_SESSION['km-user-session']['km-api-user-code'];
            $buildindCode = $_SESSION['km-user-session']['km-api-building-code'];

            $dates= array(

                'pk_prop' => $clientCode,
                'pk_cnd' => $buildindCode,
                'd_inizio' => $startDate,
                'd_fine' => $endDate
            );

            // cURL request to the receipts API
            $cURL = curl_init (KM_API);
            curl_setopt($cURL, CURLOPT_POST, 1);
            curl_setopt($cURL, CURLOPT_POSTFIELDS, http_build_query($dates)); 
            curl_setopt($cURL, CURLOPT_HEADER, 0);
            curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

            $output = curl_exec($cURL);

                if (curl_error($cURL)) {
                    // Redirect to error 500 page and die
                    header('Location: '.KM_ERROR_500);
                    exit();
                }

            curl_close($cURL);

            echo $output;

        }

        ob_start(); 
        include_once(KM_ROOT_PATH.'/km-views/km-footer.php');
        $km_footer = ob_get_contents(); 
        ob_end_clean(); 

        // Load client api receipts view
        include_once(KM_ROOT_PATH.'/km-views/km-client/km-api/km-receipts.php');

        break;

}

This is my jquery script

$(document).ready(function() {

      // Initialize air datepicker plugin
      $('.air-datepicker').datepicker();

      // Store form into variable
      var form= $("#requestForm");

      // Actions when form is submitted
      $('#submitForm').click(function(e) {

        // Ajax request
        $.ajax({

          type: "POST",
          data: form.serialize(),
          dataType:"html",
  
          success: function(result){

            // Reload the iframe with new content
            document.getElementById('tableContainer').contentDocument.location.reload(true);
            // Show the iframe
            $('#tableContainer').css('display','block');

            var $iframe = $('#tableContainer');

            $iframe.ready(function() {
                // append result to the iframe
                $iframe.contents().find("body").append(result);
                
            });


          },

          error: function(jqXHR, exception) {

            if (jqXHR.status === 0) {

              swal('Il server non risponde', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

            } else if (jqXHR.status == 404) {

              swal('Errore 404', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

            } else if (jqXHR.status == 500) {

              swal('Errore 500', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

            } else if (exception === 'parsererror') {

              swal('Si è verificato un errore!', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

            } else if (exception === 'timeout') {

              swal('Time Out', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

            } else if (exception === 'abort') {

              swal('Richiesta Annullata', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

            }

          
          }

        }); // Fine ajax
       

       e.preventDefault(); // Prevent form to be sent


      }); // fine submit form
      

    }); // fine document ready

#2

I suppose you could start by exiting after outputting:

echo $output; exit();

This should prevent outputting the html page on POST.

But I’m a bit skeptical that $output contains the desired headers so you may run into more problems.


#3

Hi just putting exit(); solves the problem. While you there as you can see in the code snippet i’m Using ob_start a few times is it correct?


#4

Your use of the ob functions is correct in the sense that you are storing snippets of html and then presumably stitching everything together in km-receipts.php. It’s not entirely clear why km-receipts.php can’t pull in the header/footer/sidebar by itself but there could be good reasons for it.

You might also want to take a look at the nowdoc syntax as an alternative to the ob functions. But again, nothing really wrong with what you are doing.