0

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. Do you suggest to use a different controller just for the ajax call?

// 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

1 Answer 1

1

Well, just put a die(); after your echo("your value"); and don't echo anything else than the string you want to get back into your ajax result.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks it works fine ;) can't believe it was that simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.