Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

and try it using ajax

$('.kirimkecontroller').click(function(){
      $.ajax({
          type: 'POST',
          url: '<?= base_url(); ?>/welcome/kiriman_dari_fetch',
          dataType: 'json',
          data: formData,
          success: function (response) {
              console.log('sukses ', response.data.status)
              window.open("<?php echo base_url(); ?>welcome/kiriman_dari_fetch", '_blank');
          }
      })
    })

put this in your head tag

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda