PHP React form formData 20: input text textarea using ajax (fetch)
Tags: php, react, form, fetch
Published: 2019-12-18 15:17:16

<hr />

<center>Happy Coding</center>

<hr />

Right now, PHP and React, the series .. 

Add external script in head tag.
First and second for <b>react</b>, and third for <b>babel</b>.

    <head>

        <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

        <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

    </head>

In body, add div tag with id="myApp" for render DOM React

        <div id="myApp" ></div>

Script React

        <script type="text/babel">

            class App extends React.Component
            {

                constructor(props)
                {

                    super(props);

                    this.state = {
                        result: {}
                    };

                    this.handleChange = this.handleChange.bind(this);
                    this.handleSubmit = this.handleSubmit.bind(this);

                }

                handleChange(event)
                {

                    const target    = event.target;

                    const name      = target.name;
                    const value     = target.value;

                    this.setState({
                        [name]: value
                    });

                }

submit function with (this) object of form

                handleSubmit(event)
                {

                    event.preventDefault();


                    var formHTML = event.target;

					console.log( formHTML ); // formHTML element


                    // https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
					var formData = new FormData( formHTML );

					console.log( formData );


                    // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

                    /* AJAX request */
                    this.ajax( formHTML, formData ); // ajax( form, data, destination = null )

                }

This, ajax fetch (promise)

                ajax( form, data, destination = null )
                {

                    fetch( form.action, {

                        method: form.method, // *GET, POST, PUT, DELETE, etc.
                        mode: 'cors', // no-cors, *cors, same-origin
                        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                        credentials: 'same-origin', // include, *same-origin, omit

                        headers: {
                            // 'Content-Type': 'application/json'
                            // 'Content-Type': 'application/x-www-form-urlencoded',
                            // "Content-Type": "multipart/form-data" // missing boundary
                        },

                        redirect: 'follow', // manual, *follow, error
                        referrer: 'no-referrer', // no-referrer, *client

                        body: data // body data type must match "Content-Type" header

                    } )

                    /* handle return result */
                    .then( response => {

                        if ( ! response.ok )
                        {
                            throw new Error(response.statusText);
                        }

                        return response.json();

                    } )

                    /* handle success */
                    .then( result => {

                        console.log( result );

                        this.setState( {result: result} );

                    } )

                    /* handle error */
                    .catch( error => {

                        console.error(error);

                    } );

                }

render it

                render() {

                    return (

                        <div>

This, Form HTML rendering

                            <form method="post" action="process.php" onSubmit={this.handleSubmit} >

                                Firstname: <input type="text" name="firstname" onChange={this.handleChange} />
                                <br />

                                Lastname: <input type="text" name="lastname" onChange={this.handleChange} />
                                <br />

                                Description: <textarea name="description" rows="10" cols="50" onChange={this.handleChange} ></textarea>
                                <br />

                                <hr />

                                <input type="submit" name="submit" value="Submit" />

                            </form>


and get input data into p tag


                            <h3>Model</h3>

                            <p>Firstname: { this.state.firstname }</p>
                            <p>Lastname: { this.state.lastname }</p>

                            <p>Description: { this.state.description }</p>

                            <hr /><br />


                            <h3>Result from server PHP</h3>

                            <pre>Submit Result: { JSON.stringify(this.state.result) }</pre>

                        </div>

                    );

                }

            }

            ReactDOM.render( <App />, document.querySelector('#myApp') )

        </script>

<hr />

process.php

    echo json_encode($_POST);

Last, don't forget press <b>F12</b>

<hr />

Demo <a href="https://repl.it" >repl.it</a>

<ul>
  <li><a href="https://repl.it/@antelove19/PHP-React-form-formData-20" >Editor</a></li>
  <li><a href="https://React-form-formData-20.antelove19.repl.co" >Live</a></li>
</ul>

<hr/>

<center>Thank for reading :)</center>

<hr/>