DEV Community

loading...

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

antelove19 profile image Falah Al Fitri ・2 min read

Happy Coding

Right now, PHP and React, the series ..

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

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

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>

                    <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 />

                        Gender:
                        <input type="radio" name="gender" value="male" onChange={this.handleChange} /> Male
                        <input type="radio" name="gender" value="female" onChange={this.handleChange} /> Female
                        <br />

                        <hr />

                        <input type="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>

                    <p>Gender: { this.state.gender }</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>

process.php

    echo json_encode($_POST);

Thank for reading :)

Discussion (0)

pic
Editor guide