DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on

PHP React form formData 20: input text textarea using ajax (fetch)


Happy Coding

Right now, PHP and React, the series ..

Add external script in head tag.
First and second for react, and third for babel.

<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>
Enter fullscreen mode Exit fullscreen mode

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

    <div id="myApp" ></div>
Enter fullscreen mode Exit fullscreen mode

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
                });

            }
Enter fullscreen mode Exit fullscreen mode

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 )

            }
Enter fullscreen mode Exit fullscreen mode

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);

                } );

            }
Enter fullscreen mode Exit fullscreen mode

render it

            render() {

                return (

                    <div>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

process.php

echo json_encode($_POST);
Enter fullscreen mode Exit fullscreen mode

Last, don't forget press F12


Demo repl.it


Thank for reading :)

Top comments (0)