Search code examples
javascriptphpfetchcodeigniter-3

Data becomes null when sending data to controller using fetch using Codeigniter 3


I have data that I want to send from a view to a controller. And I'm trying to use fetch to send it. The data has been successfully sent with a status of 200 and the data is in the request payload on the network. But when I want to try to display it in the data controller it outputs null. Does anyone have a solution to make the data is not null in the controller?

This is my script in view:

<?php
defined('BASEPATH') or exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>
</head>

<body>

    <div id="container">
        <h1>Welcome to CodeIgniter!</h1>

        <div id="body">

        <button id="kirimkecontroller">Kirim</button>

        <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
    </div>
    <script>
        // var data = {
        //  'testing': 'isi testing'
        // }

        let formData = new FormData()
        formData.append('testing', 'isi testing')

        const button = document.querySelector('#kirimkecontroller')
        button.addEventListener('click', () => {
            fetch("<?= base_url(); ?>/welcome/kiriman_dari_fetch", {
                    method: "POST",
                    mode: 'no-cors',
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: formData,

                }).then(res => console.log('sukses ', res.status))
                .catch(e => console.log('gagal ', e));

            window.open("<?php echo base_url(); ?>welcome/kiriman_dari_fetch", '_blank');
        })
    </script>


</body>

</html>

And This is my script in controller:

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Welcome extends CI_Controller
{

    public function index()
    {
        $this->load->view('welcome_message');
    }

    public function kiriman_dari_fetch()
    {
        $testing = $this->input->post('testing');
        echo json_encode($testing); // null
    }
}

And output is null

In Inspect Element > Nework:

enter image description here

How do I get the data from there to the controller?


Solution

  • As I understand your problem is you're trying to send a POST request to that controller and want to display the post's data after that on a new tab, right?

    If it is, please remember that those are two separate requests: when you send POST request by fetch or jquery the controller already receive your data and response to that request by:

    echo json_encode($testing);
    

    so you can see response in Inspect Element > Network:

    But when you open a new blank window, it's a different GET request, so there's is null value when you try to print it. You can check that by using this snippet:

    public function kiriman_dari_fetch()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $testing = $this->input->post('testing');
            echo json_encode($testing);
        } else {
            $data = array();
            $data['request_type'] = 'THIS IS GET';
            $this->load->view('welcome_message', $data); // change welcome_message to another of your views
        }
    }
    

    Add $request_type to view to check GET or POST request:

    <body>
    
        <div id="container">
            <h1>Welcome to CodeIgniter!</h1>
    
            <div id="body">
    
                <button id="kirimkecontroller">Kirim</button>
    
                <p><?php echo $request_type; ?></p>
    ....
    </html>
    

    When you open that URL on a browser, it will display "THIS IS GET"

    Back to your problem, you can use the response of your post request and then update the current view by jquery or html selector.