DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on • Edited on

1 1

PHP jQuery form formData 60: input text textarea file using ajax ($.ajax)


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

        // https://api.jquery.com/jquery.each/
        /*
         *  array.each( function( index, element ) )
         *  $.each( array, callback )
         */

        // https://www.w3schools.com/jquery/misc_each.asp

        /* get all form */
        $( "form" ).each( function () {

            /* each form add onsubmit event */
            $( this ).bind( "submit", function (event) {

                event.preventDefault(); // return false


                var formHTML = event.target; // $( this ) => not work !!

                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://api.jquery.com/jquery.ajax/
                // https://www.w3schools.com/jquery/ajax_ajax.asp
                // https://www.w3schools.com/jquery/jquery_ref_ajax.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 )
        {

            $.ajax({

                method: form.method,
                url: form.action,

                data: data,

                /*
                    result type data
                    JSON.parse(data)
                    http://api.jquery.com/jQuery.ajax/
                    https://stackoverflow.com/questions/14322984/differences-between-contenttype-and-datatype-in-jquery-ajax-function
                    https://forums.asp.net/t/2087039.aspx?what+is+difference+between+dataType+and+contentType+in+jquery
                */
                dataType: "HTML",

                /* formData */
                contentType: false, // formData with $_POST or $_FILES in server (PHP)
                processData: false

            })

            /* handle success */
            .done( function(result) {

                $( destination ).html( result );

                console.log(result);

            } )

            /* handle error */
            .fail( function(error) {

                alert("Cannot Set Data!");

                console.error(error);

            } );

        }

    </script>
Enter fullscreen mode Exit fullscreen mode

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

    <script>

        /* preview image */
        $( "input[type='file']" ).on( "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

echo "<pre>";

var_dump($_POST);

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

Demo repl.it


Thank for reading :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay