DEV Community

loading...

PHP React form formData 10: input text 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.

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

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

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

Last, don't forget press F12


Demo repl.it


Thank for reading :)

Discussion (0)

pic
Editor guide