skip to Main Content

When I try to type data into reactJs form through the API, the console returns null.

When I refresh the page on the backend CodeIgniter, it then displays the key values in the form of null.

How can I fix the problem data so that the console does not return null when I input through a reachJS form.

For instance, when I type in browser http://localhost/API/UserController/users, it returns null on every response of the reactJs form as follows:

{"user_id":"119","UserName":null,"user_email":null,"Password":null,"CreatedDate":"0000-00-00 00:00:00","Status":null,"Role":null,"VendorId":null}

When I check the code in
http://localhost/API/UserController/insertUsers, only the insertUser controller returns null.

Any input in regards to the problem would be appreciated.
My database code is:

CREATE TABLE `users`(
    `user_id` int(11) NOT NULL,
    `UserName` varchar(255) DEFAULT NULL,
    `user_email` varchar(40) DEFAULT NULL,
    `Password` varchar(1000) DEFAULT NULL,
    `CreatedDate` datetime DEFAULT NULL,
    `Status` int(11) DEFAULT NULL
    `Role` varchar(255) DEFAULT NULL,
    `VendorId` int(11) DEFAULT NULL
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

My Usermodel in CodeIgniter is:

class Usermodel extends CI_Model
{

public function get_users(){
    $query = $this->db->select("*")
              ->from("users")
              ->get();
    return $query;      
}
public function insert_users($data){
    $this->UserName = $data['UserName'];
    $this->user_email=$data['user_email'];
    $this->Password =$data['Password'];
    $this->CreatedDate=$data['CreatedDate'];
    $this->Status=$data['Status'];
    $this->Role = $data['Role'];
    $this->VendorId=$data['VendorId'];
    $this->db->insert("users",$this);
}
}

My UserController Controller in insertUsers Method is:

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
header('Access-Control-Allow-Origin: *');
if($_SERVER['REQUEST_METHOD']==='OPTIONS'){
    header('Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS');
    header('Access-Control-Allow-Headers:Content-Type');
    exit;
}
class UserController extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model("usermodel","us");
    }
    public function users(){
        $query = $this->us->get_users();
        header("Content_Type:application/json");
        echo json_encode($query->result());
    }
    public function insertUsers(){
        $data = array(
            'UserName'      =>$this->input->post('UserName') ,
            'user_email'    =>$this->input->post('user_email'),
            'Password'      =>$this->input->post('Password'),
            'CreatedDate'   =>date("l jS of F Y h:i:s A"),
            'Status'        =>$this->input->post('Status'),
            'Role'          => $this->input->post('Role'),
            'VendorId'      => $this->input->post('VendorId'), 
        );
        $query =$this->us->insert_users($data);
        header("Content_Type:application/json");
        echo json_encode($query);
    }
}

Additionally, I fetch the API using reactJS, and when the user writes any data in form, it returns null in response Register.js as follows:

import React, { Component } from 'react';
import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';

class Register extends Component {
  constructor(props){
    super(props);
    this.state = {
      user_id:'',  Username:'', Password:'', user_email:'',CreatedDate:'',Status:'',Role:'',VendorId:'',
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
    handleChange(event){
    const state = this.state;
    state[event.target.name] = event.target.value;
    this.setState(state, () => console.log(state));
    // console.log(state); state get undefined
    }  

handleSubmit(event){
    event.preventDefault();
    fetch('http://localhost/API/UserController/insertUsers',{
      method:'POST',
      headers:{
        'Content-Type':'application/json',
        'Accept':'application/json'
      },
      body:JSON.stringify({
        user_id :this.state.user_id,
        Username:this.state.Username,
        Password:this.state.Password,
        user_email:this.state.user_email,
        CreatedDate:this.state.CreatedDate,
        Status:this.state.Status,
        Role: this.state.Role,
        VendorId:this.state.VendorId,
      })
    })
      .then(res =>res.json() )
      .then(data => console.log(data))
      .catch(err => console.log("show me error that cannot be specify",err))
  }
  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          <Row className="justify-content-center">
            <Col md="9" lg="7" xl="6">
              <Card className="mx-4">
                <CardBody className="p-4">
                  <Form action="http://localhost/API/UserController/users" method="post" onSubmit={this.handleSubmit}>
                    <h1>Register</h1>
                    <p className="text-muted">Create your account</p>
                    <InputGroup className="mb-3">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="icon-user"></i>
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input required  type="text" name="UserName" value={this.state.UserName} onChange={this.handleChange} placeholder="Username" autoComplete="username" name="Username"  />
                    </InputGroup>
                    <InputGroup className="mb-3">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>@</InputGroupText>
                      </InputGroupAddon>
                      <Input required  type="text" placeholder="User email" name="user_email" value={this.state.user_email} onChange={this.handleChange} autoComplete="email" />
                    </InputGroup>
                    <InputGroup className="mb-3">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="icon-lock"></i>
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input required  type="password" placeholder="Password" value={this.state.Password} onChange={this.handleChange} name="Password" autoComplete="new-password" />
                    </InputGroup>
                    <Button color="success" block>Create Account</Button>
                  </Form>
                </CardBody>
                <CardFooter className="p-4">
                  <Row>
                    <Col xs="12" sm="6">
                      <Button className="btn-facebook mb-1" block><span>facebook</span></Button>
                    </Col>
                    <Col xs="12" sm="6">
                      <Button className="btn-twitter mb-1" block><span>twitter</span></Button>
                    </Col>
                  </Row>
                </CardFooter>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

export default Register;

2

Answers


  1. Chosen as BEST ANSWER

    Usermodel

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Usermodel extends CI_model {
    
      public function get_users()
      {
        $this->db->where('is_active', 1);
        $query = $this->db->get('users');
        return $query->result();
      }
    
      public function insert_users($formData)
      {
        $this->db->insert('users', $formData);
        return $this->db->insert_id();
      }
    }
    

    My UserController Controller in insertUsers Method is:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class UserController extends CI_Controller {
      public function __construct()
      {
        parent::__construct();
        $this->load->model('Usermodel');
      }
    
      public function users()
      { 
        header("Access-Control-Allow-Origin: *");
        $users = $this->Usermodel->get_users();
    
        $this->output
          ->set_content_type('application/json')
          ->set_output(json_encode($users));
      }
    
    
    
      public function insertUsers()
      { 
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");
    
        $formdata = json_decode(file_get_contents('php://input'), true);
    
        if( ! empty($formdata)) {
    
          $UserName = $formdata['UserName'];
          $user_email = $formdata['user_email'];
          $Password = $formdata['Password'];
    
          $userData = array(
            'UserName' => $UserName,
            'user_email' => $user_email,
            'Password' => password_hash($Password,PASSWORD_DEFAULT),
             'is_active' => 1,
            'created_at' => date('Y-m-d H', time())
          );
    
          $id = $this->Usermodel->insert_users($userData);
    
          $response = array(
            'status' => 'success',
            'message' => 'User Register successfully'
          );
        }
        else {
          $response = array(
            'status' => 'error'
          );
        }
    
        $this->output
          ->set_content_type('application/json')
          ->set_output(json_encode($response));
      }
    }
    

    Register.js code store data in database now

    import React, { Component } from 'react';
    import { Button, Card, CardBody, CardFooter, Col, Container,Alert, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
    class Register extends Component {
      constructor(props){
        super(props);
        this.state = {
          Username:'',
          user_email:'',
          Password:'',
          error:null,
          response:{},
        }
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
        handleChange(event){
        const name  = event.target.name;
        const value = event.target.value;
    
        this.setState({
          [name]: value
        });
        } 
    
        handleSubmit=(event)=>{
         event.preventDefault();
         this.onFormSubmit(this.state);
         this.setState(this.state);
    
        }
        onFormSubmit(data){
          const apiUrl = "http://localhost/API/UserController/insertUsers";
          const myHeaders = new Headers();
          myHeaders.append('Content-Type','application/json');
          const options = {
            method:'POST',
            body:JSON.stringify(data),
            myHeaders
          };
          fetch(apiUrl,options)
            .then(res => res.json() )
            .then(result =>{
              this.setState({
               response:result,
             });
            })
            .then(error=>{
              this.setState({
                error
              });
            });
    
            this.setState({
            Username:'',
            user_email:'',
            Password:''
            });
        }
      render() {
        return (
            <div className="app flex-row align-items-center">
            <Container>
              <Row className="justify-content-center">
                <Col md="9" lg="7" xl="6">
                  <Card className="mx-4">
                    <CardBody className="p-4">
                      <Form onSubmit={this.handleSubmit}>
                        <h1>Register</h1>
                        <p className="text-muted">Create your account</p>
                        <InputGroup className="mb-3">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="icon-user"></i>
                            </InputGroupText>
                          </InputGroupAddon>
                          <Input   type="text" name="UserName" value={this.state.UserName} onChange={this.handleChange} placeholder="Username" autoComplete="username"   />
                        </InputGroup>
                        <InputGroup className="mb-3">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>@</InputGroupText>
                          </InputGroupAddon>
                          <Input   type="text" placeholder="User email" name="user_email" value={this.state.user_email} onChange={this.handleChange} autoComplete="email" />
                        </InputGroup>
                        <InputGroup className="mb-3">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="icon-lock"></i>
                            </InputGroupText>
                          </InputGroupAddon>
                          <Input   type="password" placeholder="Password" value={this.state.Password} onChange={this.handleChange} name="Password" autoComplete="new-password" />
                        </InputGroup>
                        <Button color="success" block>Create Account</Button>
                      </Form>
                    </CardBody>
                    <CardFooter className="p-4">
                      <Row>
                        <Col xs="12" sm="6">
                          <Button className="btn-facebook mb-1" block><span>facebook</span></Button>
                        </Col>
                        <Col xs="12" sm="6">
                          <Button className="btn-twitter mb-1" block><span>twitter</span></Button>
                        </Col>
                      </Row>
                    </CardFooter>
                  </Card>
                </Col>
              </Row>
            </Container>
                      {this.state.response.status === 'success' && <div><br /><Alert variant="info">{this.state.response.message}</Alert></div>}
                                {this.state.error && <div>Error: {this.state.error.message}</div>}
          </div>
        );
      }
    }
    export default Register;
    

  2. CodeIgniter does not return data or a result set when you perform write operations like insert or update on a database, it returns a boolean instead (true/false).
    Thus why you’re getting null, the value of $query here

    $query = $this->us->insert_users($data);
    

    Will be true if the operation is successful, else will be false.

    Use an if statement to check if true and return $data instead

    echo json_encode($data);
    

    You can checkout CI (CodeIgniter)’s documentation on queries here
    https://www.codeigniter.com/user_guide/database/queries.html

    I also suggest you use an encryption algorithm to encrypt your password.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search