Link to home
Start Free TrialLog in
Avatar of tf2012
tf2012

asked on

PHP ReactJS/Axios Ajax POST to codeigniter problem

On the codeigniter side the post data isn't being received.  PHP is however receiving it.

Here is the ajax call
   
    var postData = {
        'partNumber' : '45367'
    }
axios.post('http://localhost/stuff/index.php/admin/reactTestaroo', postData)
        .then(response => renderTheTestData(response.data))

Open in new window


Here is what is in my PHP/CI controller:
    function reactTestaroo(){
        $entityBody = file_get_contents('php://input'); // just as a test I used this and it returns "{'partNumber':'45367'}" which seems to indicate it's being passed fine
        $pastNumber = $this->input->post('partNumber'); // returns NULL, this is the problem.. it should show the part number value.  
    }

Open in new window


I can use jQuery ajax all day long and it works fine like this:
    $.ajax({
        url: 'http://localhost/stuff/index.php/admin/reactTestaroo',
        data: postData,
        type: 'POST',
        success: function(response) {
        var parsedJSON = $.parseJSON(response);
        renderTheTestData(parsedJSON.part_name)
        },
        error: function(response){
            alert('nope');
        }
    });

Open in new window

With jQuery it works every time but I want to ditch jQuery and use react and a ajax plugin like axios but clearly I'm having an issue with it.  Can someone help me get the ajax via axios working?
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

I don't understand this part
On the codeigniter side the post data isn't being received.  PHP is however receiving it.
What is the difference between CI and PHP?
Avatar of tf2012
tf2012

ASKER

Using $entityBody = file_get_contents('php://input');  I can see that the values are being passed to PHP, however using $this->input->post I get null.  When I use jQuery, the value shows up in $this->input->post just fine.  I hope that helps
file_get_contents('php://input') gets the raw post data - which is not always accessible through POST

For instance if the data posted to the service is JSON it won't be accessible by post - you have to use file_get_contents('php://input'); and then decode the JSON

$raw = file_get_contents('php://input');
$data = json_decode($raw);

Open in new window

Avatar of tf2012

ASKER

ok thanks, any idea how to force it to use post?  I don't necessarily need to submit it as JSON it could be a form submission format.. I'll play with that idea and maybe you have some thoughts about that.  Otherwise I'll have to use your suggestion of parsing it out of php://input
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tf2012

ASKER

thank you!
You are welcome.