30 September 2016

Create Operation on Database Table Through Rest Service Using Ajax and ReactJS/React.js

Hi Friends,

In this post I am going to show you the Create Operation of CRUD by using ReactJS or React.js with the help of Restful webservice call via Ajax.

Let's say I have a restful webservice built on database table named "Departments" in HR Schema of Oracle XE database. This restful service is having an "/add" method to insert the new record in Departments table. The service accept the JSON data as the input and insert it to database.

We are showing all the records available in the Departments table using ajax call and rendering with help of ReactJS which you can see in the below post :

http://www.code4fusion.com/2016/09/column-level-filter-in-fixed-data-table.html

Now we will add a Add Departments facility to the above example and insert the data in database table using ReactJS.

For this I have modified the code of the table render function as follows:

render: function(){
 var rows = this.state.departments;
 var h= rows.length*30+85;
    return (
    <div>
    <div  style={divStyleRight}>
  <h1> Enter Department </h1>
       <input name="departmentId" ref="departmentId" type="text" id="departmentId" placeholder="Department Id" /><br/><br/>
       <input name="departmentName" ref="departmentName" type="text" id="departmentName" placeholder="Department Name" /><br/><br/>
       <input name="Submit" value="Submit" type="Submit" onClick = {this.submitForm}/>
</div>
    <div  style={divStyleLeft}>
    <Table
      filterable={['id', 'departmentId', 'departmentName']}
      noDataText="No matching records found"
      height={h}
      width={600}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={80}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
      <Column dataKey="id" width={200} height={50} label="Searial Number" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentId" width={200} label="Department Id" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentName" width={200} label="Department Name" headerRenderer={this.renderHeader}/>
    </Table>
    </div>
    </div>);
     }


we have defined two style variable as follows:

var divStyleLeft = {
 width: '50%', float:'left'
};

var divStyleRight= {
 width: '50%', float:'right'
}; 



The purpose of defining these two style is to divide the main DIV in two equal parts, so that we can put our table on left side and form on the right side.

we are referring the style as follows in our code:

 <div  style={divStyleRight}> and <div  style={divStyleLeft}>

After this our page will look like this:


Now our UI part is done. Now we will add a method to handle the submit button event. For this I have written the following lines of code:

submitForm: function(event) {   
   var lastIndex = this.state.departments.length;
   var dept = {"departmentId": this.refs.departmentId.value,"departmentName" :this.refs.departmentName.value};
   var deptVirtual = {"id": lastIndex+1, "departmentId": this.refs.departmentId.value,"departmentName" :this.refs.departmentName.value};
   this.setState({departments:this.state.departments.concat([deptVirtual])});
   console.log(this.state.departments);
        $.ajax({
                 type: "POST",
                 url: this.props.dataUrl+"add",
                 data: JSON.stringify(dept),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
               
                 alert("New department added successfully");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });     
  }


To call this method we need to specify "onClick = {this.submitForm}" on the Submit button.

So after the above modification your jsx code should look like this:

import React from "react";
import ReactDOM from "react-dom";
import {Table, Column, Cell} from 'fixed-data-table';

var divStyleLeft = {
 width: '50%', float:'left'
};

var divStyleRight= {
 width: '50%', float:'right'
};


var DepartmentGridTable = React.createClass({
 getInitialState: function() {
    return {departments: [],  departments1:[], rows:[]};
  },
    
 renderHeader(label, cellDataKey) {
  return <div>
        <span>{label}</span>
          <div>
            <br />
            <input type="text" onChange={this.onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
},

onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      departments: this.state.departments1,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.state.departments1.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.state.departments1[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.state.departments1[index]);
    }
  }
  this.setState({
    departments: filteredList,
  });
},
submitForm: function(event) {  
   var lastIndex = this.state.departments.length;
   var dept = {"departmentId": this.refs.departmentId.value,"departmentName" :this.refs.departmentName.value};
   var deptVirtual = {"id": lastIndex+1, "departmentId": this.refs.departmentId.value,"departmentName" :this.refs.departmentName.value};
   this.setState({departments:this.state.departments.concat([deptVirtual])});
   console.log(this.state.departments);
        $.ajax({
                 type: "POST",
                 url: this.props.dataUrl+"add",
                 data: JSON.stringify(dept),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                
                 alert("New department added successfully");
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });     
  },

componentDidMount: function() {
     $.ajax({
      url: this.props.dataUrl,
      dataType: 'json',
      success: function(data) {
     
      var deptArray=[];

var arrayLength = data.length;
for (var i = 0; i < arrayLength; i++) {
deptArray.push(
{                     
                        "id" : i+1,
                        departmentId: data[i].departmentId,
                        departmentName:  data[i].departmentName
                    });

}
         this.setState({departments: deptArray});
         this.setState({departments1: deptArray});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.dataUrl, status, err.toString());
      }.bind(this)
    });
  },
 render: function(){
 var rows = this.state.departments;
    return (
    <div>
    <div  style={divStyleRight}>
  <h1> Enter Department </h1>
       <input name="departmentId" ref="departmentId" type="text" id="departmentId" placeholder="Department Id" /><br/><br/>
       <input name="departmentName" ref="departmentName" type="text" id="departmentName" placeholder="Department Name" /><br/><br/>
       <input name="Submit" value="Submit" type="Submit" onClick = {this.submitForm}/>
</div>
    <div  style={divStyleLeft}>
    <Table
      filterable={['id', 'departmentId', 'departmentName']}
      noDataText="No matching records found"
      height={500}
      width={600}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={80}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
      <Column dataKey="id" width={200} height={50} label="Searial Number" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentId" width={200} label="Department Id" headerRenderer={this.renderHeader}/>
      <Column dataKey="departmentName" width={200} label="Department Name" headerRenderer={this.renderHeader}/>
    </Table>
    </div>
    </div>);
     }

 });

ReactDOM.render(
 <DepartmentGridTable dataUrl ="http://localhost:9001/TestRestEasy/rest/departments/"/>,
  document.querySelector("#container")
);
 


And you html file should look like this:

 <!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fixed-data-table/0.6.3/fixed-data-table.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fixed-data-table/0.6.3/fixed-data-table.min.css"></script>
 <link href="https://cdnjs.cloudflare.com/ajax/libs/fixed-data-table/0.6.3/fixed-data-table.css" rel="stylesheet">
</head>
<body>
  <div id="container"></div>
  <script src="output/myCode.js"></script>
</body>
</html>


Now open your application in the browser and run your page.

 Now enter the Department Id and Department Name in the text fields on the right side and click on submit.


 You will get the confirmation message as "New department added successfully" as shown below:

 
 Click on OK and now scroll down in your table to see the newly created row:

Now let's go and check in the database whether this record is created there in the Departments table or not by running the query in SQL Developer as shown below:



So in the above screenshot we can see that the record is created in the database as well.

Happy Coding :)

 

0 on: "Create Operation on Database Table Through Rest Service Using Ajax and ReactJS/React.js"