1

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?

Raazescythe
  • 117
  • 1
  • 20

2 Answers2

1

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.

Canh
  • 516
  • 1
  • 3
  • 9
  • so does the data actually already exist in the controller? – Raazescythe Aug 29 '21 at 07:18
  • Yes, 'isi testing' you received in browser is the response from your controller – Canh Aug 29 '21 at 07:20
  • actually I want to send it to the model, to do some conditioning on the query, but the data always reads null, is there any way I can do it sir? – Raazescythe Aug 29 '21 at 07:35
  • As I said, your controller already received it. You can use that to query in your model. You can use this as an example: https://codeigniter.com/userguide3/tutorial/create_news_items.html#model. Feel free to post your code in this post so I can help to if there's any problem – Canh Aug 29 '21 at 07:39
  • I still don't understand how to make sure that the post result data exists, if it's null isn't it that we can't do conditioning? – Raazescythe Aug 29 '21 at 08:12
  • If you want to display the data of that post request to make sure if it is null or not, add the load view to function kiriman_dari_fetch() like I did above. And try to get through the codeigniter tutorial in https://codeigniter.com/userguide3/tutorial/create_news_items.html#create-a-form. The create function in that both handle the get and post request – Canh Aug 29 '21 at 08:59
  • Thank you very much for the explanation, apparently I misunderstood earlier. Thank you very much for your help sir. – Raazescythe Aug 29 '21 at 10:27
  • now I found a new problem, is it possible to send the data to a new tab? – Raazescythe Aug 29 '21 at 14:05
  • Sure, you can use the way in this link: https://stackoverflow.com/questions/24908686/jquery-open-page-in-a-new-tab-while-passing-post-data. Before open new window, store your data to the SESSION and then after open new window, check if that data exists – Canh Aug 29 '21 at 14:18
  • is there no other way than to store the data in the session? – Raazescythe Aug 29 '21 at 16:32
  • I don't know much about what's you want to do but if you want to store the data maybe this [link](https://stackoverflow.com/questions/1830347/quickest-way-to-pass-data-to-a-popup-window-i-created-using-window-open). You can edit your question and post your code there so I can understand more what's your problem – Canh Aug 30 '21 at 01:08
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>