PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 6, 2022

[FIXED] Can't access fetch post data in controller: Codeigniter

 January 06, 2022     codeigniter, fetch     No comments   

Issue

I'm making a post request using fetch in my codeigniter project. The request looks like this

fetch('myurl/mycontroller', {
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
         testdata: 123,
    })
 }).then((res) => {
    console.log(res);
 }).catch(console.log);

My controller looks like below

class MyController extends CI_Controller
{
    public function mycontroller()
    {
        $data = $this->input->post('testdata');
        return $data . " is the passed data.";
    }
}

But the data isn't getting passed to my controller. I echoed out $_POST and it gave me an empty array. Any idea what I'm doing wrong? I'm using codeigniter 2 (which I know is very old now)


Solution

So not completely sure about the actual reason but there might be some bug with the CI core of codeigniter which doesn't parse the data passed to controller using fetch. Using FormData() and axios I was able to resolve the issue.

 var postData = new FormData();
 postData.append('testdata', 123);
 axios.post('myurl/mycontroller', postData).then(function(response){
     console.log("success:", response);
 }).catch(function(error){
     console.log("error:", error);
 });


Answered By - Justin S
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing