0

The following is the react code used to create UI. I added the code to store the data to MySQL. This part is not working.

ContactUsClass.js

import React from 'react';
require('./styles.css');
//my SQL code (not working) - start
require('node-mysql');
var mysql = require('mysql');
//my SQL part - end
class ContactUsClass extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            text: {
                n: '',
                m: '',
                p: '',
                msg:''
            }
        };
        this.handleSubmit = this
            .handleSubmit
            .bind(this);
    }
    handleChange(pty, event)
    {
        const text = this.state.text;
        text[pty] = event.target.value;
        this.setState({text: text});
    }

    handleSubmit(event)
    {
        alert('Text field value is: ' + this.state.text.e + '\nExtra:' + this.state.text.c + '\nTA:' + this.state.text.msg);
        //mysql code (not working) - start
        var connection = mysql.createConnection({host: '127.0.0.2', user: 'root', password: 'admin', database: 'dbcontactus'});
        connection.connect(function (err) {
            if (!err) {
               alert("Database is connected ... ");
            } else {
                alert("Error connecting database ... ", err);
            }
        });

        var user = {
            'clientname': 'CH Yamini Sankar',
            'email': 'mail@mail.com',
            'phonenumber': '9999454551',
            'message': 'hello world'
        };
        connection.query('Insert into tbcontactus SET ?', user, function (err, res) {
            connection.end();
            if (!err) 
                alert('The solution is: ', res);
            else 
                alert('Error while performing Query.', err);
            }
        );
        //mysql code (not working) - end
    }
    render()
    {
        return (
            <div className="mainbox">
                <div className="heading">
                    Contact Us</div>
                <div><br/></div>
                <div>
                    <input
                        className="tbox"
                        type="text"
                        placeholder="Name"
                        value={this.state.text.e}
                        onChange={this
                        .handleChange
                        .bind(this, 'e')}/>
                    <input
                        className="tbox"
                        type="text"
                        placeholder="E-mail ID"
                        value={this.state.text.c}
                        onChange={this
                        .handleChange
                        .bind(this, 'c')}/>
                </div>
                <div>
                    <input
                        className="tpbox"
                        type="text"
                        placeholder="Mobile/Phone no: +1"
                        value={this.state.text.p}
                        onChange={this
                        .handleChange
                        .bind(this, 'p')}/>
                </div>

                <div>
                    <textarea
                        className="mbox"
                        type="text"
                        placeholder="Message"
                        value={this.state.text.msg}
                        onChange={this
                        .handleChange
                        .bind(this, 'msg')}/>
                </div>

                <div>
                    <button className="btn" onClick={this.handleSubmit}>Submit</button>
                </div>
            </div>
        );
    }
}

export default ContactUsClass;

ContactUsMain.js

import React from 'react';
import ReactDOM from 'react-dom';
import ContactUsClass from './ContactUsClass.js';

ReactDOM.render(
    <ContactUsClass/>, document.getElementById('container'));

ContactUs.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Contact Us</title>
</head>

<body>
    <div id="container"></div>
    <script src="BundleContactUs.js"></script>
</body>

</html>

webpack.config.js

var config = {
    entry: './ContactUsMain.js',

    output: {
        path: './',
        filename: 'BundleContactUs.js'
    },

    devServer: {
        inline: true,
        port: 8080
    },

    module: {
        loaders: [{
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['latest', 'react']
                }
            }, {
                test: /\.css?$/,
                exclude: /node_modules/,
                loader: 'style-loader!css-loader'
            }

        ]
    },
    node: {
        net: 'empty',
        tls: 'empty',
        dns: 'empty',
        fs: 'empty'
    }
}

module.exports = config;

package.json

{
    "name": "hrportal",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "start": "webpack-dev-server --hot",
        "test": "node ContactUsConn.js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "babel-core": "^6.18.2",
        "babel-loader": "^6.2.8",
        "babel-preset-latest": "^6.16.0",
        "babel-preset-react": "^6.16.0",
        "css-loader": "^0.26.0",
        "mysql": "github:mysqljs/mysql",
        "node-mysql": "^0.4.2",
        "popup": "0.0.3",
        "react": "^15.4.0",
        "react-dom": "^15.4.0",
        "style-loader": "^0.13.1",
        "webpack": "^1.13.3",
        "webpack-dev-server": "^1.16.2"
    }
}

The following is the styles.css

.mainbox {
    width: 40%;
    margin: 0 auto;
    height: 500px;
    background-color: white;
}

.lbox {
    width: 50px;
    float: left;
    height: 100px;
    background-color: maroon;
}

.rbox {
    width: 50px;
    float: right;
    height: 100px;
    background-color: maroon;
}

.heading {
    width: 25%;
    padding: 15px;
    border-bottom-style: solid;
    border-radius: 5px;
    border-bottom-color: gray;
    margin: 0 auto;
    font-size: 24px;
    font-weight: 500;
    font-family: 'Roboto', sans-serif;
    text-align: center;
    color: gray;
}

.tbox {
    width: 48%;
    height: 35px;
    padding: 4px;
    margin: 1%;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.tpbox {
    width: 98%;
    height: 35px;
    padding: 4px;
    margin: 1%;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.mbox {
    width: 98%;
    padding: 4px;
    height: 125px;
    margin: 1%;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.btn {
    width: 100px;
    height: 35px;
    padding: 4px;
    margin: 0 auto;
}

body {
    background-color: #F0EDED;
}

Using the above five files I want to store the data from the web page to the database and vice-versa.

Yamini Sankar
  • 29
  • 1
  • 6

1 Answers1

3

You are attempting to directly access the MySQL database through client side code, but that should be done on your server. For more information on this, see this question/answer

What you should be doing on the client side is submitting the data through an ajax call. Then, on your server you should parse the request and insert the data into your database.

Example

In your ContactUs component, you would submit the data to your server. The example below uses the Fetch API.

ContactUs.jsx

class ContactUs extends React.Component {

  handleSubmit(event) {
    var user = {
        'clientname': 'CH Yamini Sankar',
        'email': 'mail@mail.com',
        'phonenumber': '9490430491',
        'message': 'hello world'
    };

    fetch('/api/contact-us', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(user)
    })
  }

  render() {
    // ...
  }

}

The language of the server is up to you, but since we're discussing JavaScript, I'll show a node server that uses express.

server.js

app.use(express.bodyParser());

app.post('/api/contact-us', (req, res) => {
  // connect to your MySQL database and insert the data
})
Community
  • 1
  • 1
Paul S
  • 35,097
  • 6
  • 41
  • 38
  • Thanks Paul. Is there any other way to do it without using ajax. Can you provide example for this please. – Yamini Sankar Nov 28 '16 at 05:36
  • I added an example and a link to another SO question that should explain why you can't access your DB through the client. You don't have to use AJAX, you can just do a regular form submission, but that will obviously reload your app, which you may or may not want to have happen. – Paul S Nov 28 '16 at 06:41
  • Added code to server.js as follows: app.use(express.bodyParser()); app.post('/api/contact-us', (req, res) => { var connection = mysql.createConnection({ host: '127.0.0.2', user: 'root', password: 'admin', database: 'dbcontactus' }); connection.connect(function(err) { if (!err) { alert("connected ... "); } }); connection.query('Insert into tbcontactus SET ?', user, function(err, res) { connection.end(); if (err) alert('Error.', err); }); }). Still data is not stored in database. – Yamini Sankar Nov 28 '16 at 09:57
  • Where and how to invoke server.js? – Yamini Sankar Nov 28 '16 at 10:00
  • What I wrote wasn't a complete solution, you'll have to fill in the blanks on your own. The server.js file is supposed to be run on your server. It isn't a complete solution, just a snippet showing where to receive the user's submission. You'll need to learn about server side scripting if you are unsure of how to do this. – Paul S Nov 28 '16 at 17:16
  • I add the code to the files. Also posted them in the comments. Please check. Appreciate your help. Can you suggest an working example for this scenario? – Yamini Sankar Nov 29 '16 at 04:36