DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on • Edited on

2 1

PHP Javascript form formData 60: input text textarea file using ajax (XMLHttpRequest)


Happy Coding

index.php

    <form method="post" action="process.php" >

        Firstname: <input type="text" name="firstname" />
        <br />

        Lastname: <input type="text" name="lastname" />
        <br />

        Description: <textarea name="description" rows="10" cols="50" ></textarea>
        <br />

        File Upload: <input type="file" name="upload" /><br />
        preview: <img src="#" />
        <br />

        <hr />

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

    </form>

    <hr />
Enter fullscreen mode Exit fullscreen mode

display result form server

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

get formHTML element and add onsubmit event, and create formData, then call ajax function with arguments formHTML, formData and output display ("#output")

    <script>

        /* submit form */
        document.querySelector( "form" ).addEventListener( "submit", function (event) {

            event.preventDefault(); // return false


            var formHTML = event.target; // this

            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/XMLHttpRequest
            // https://www.w3schools.com/xml/xml_http.asp
            // https://www.w3schools.com/js/js_ajax_http.asp

            /* AJAX request */
            ajax( formHTML, formData, "#output" ); // ajax( form, data destination )

        });

    </script>
Enter fullscreen mode Exit fullscreen mode

ajax function

    <script>

        function ajax( form, data, destination )
        {

            if (window.XMLHttpRequest)
            {
                var xhr = new XMLHttpRequest(); /* code for modern browsers */
            }
            else
            {
                var xhr = new ActiveXObject("Microsoft.XMLHTTP"); /* code for old IE browsers */
            }

            xhr.open( form.method, form.action, true ); // ( "post", "process.php", true )
            xhr.send( data );

            xhr.onreadystatechange = function () {
                if ( this.readyState == 4 && this.status == 200 )
                {
                    document.querySelector( destination ).innerHTML = this.responseText;
                }
            };

        }

    </script>
Enter fullscreen mode Exit fullscreen mode

add onchange event in input with file type, then display it with img tag

    <script>

        /* preview image */
        document.querySelector( "input[type='file']" ).addEventListener( "change", function () {

            var preview = document.querySelector( "img" );
            var file    = document.querySelector( "input[type='file']" ).files[0];
            var reader  = new FileReader();

            reader.addEventListener( "load", function () {
                preview.height = 100;
                preview.title  = file.name;
                preview.src    = reader.result;
            }, false );

            if (file)
            {
                reader.readAsDataURL(file);
            }

            console.log( reader );

        } );

    </script>
Enter fullscreen mode Exit fullscreen mode

process.php

$data = array(
    "post"  => $_POST,
    "files" => $_FILES
);

echo "<pre>";

var_dump($data);

echo "</pre>";
Enter fullscreen mode Exit fullscreen mode

Demo repl.it


Thank for reading :)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay