PHP, Ajax, and Jquery Using Serialize To Post All Form Data

This simple lesson will show how to use the Jquery serialize() function to pass all form data to an ajax file. With the serialize() function, it is very easy to pass all form data name and values to the ajax file without having to send them all separately.

I will go over this in detail. When the user inputs a name in the text input box and clicks 'Submit it', the Jquery .submit() method is triggered. We pass in the e into the function and use e.preventDefault() method too because you do not want the usual form submission to happen....which would be a typical post request that would reload the page.

After that, the formData variable is created and it contains the names and values from the form. Then, it is passes into Ajax for which it is sent to the ajax_1.php file.

After it arrives to the ajax_1.php file, the parse_str() function is used to make an array from that serialized data. In that array, is the first name that was entered into the text field. Thus, the value of that posted test becomes $myArray['myFirst']. Remember that myFirst was the name of the input text box.

After that, it is pretty much a simple mySQL query that finds all users with that first name. Finally, the names are printed in two separate 'div' elements. Note that the printed text in the ajax file is handled as the msg variable in the original file.

Thus, there are two places and methods for which the same text is printed; one using vanilla javascript and the other using Jquery.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $('form').submit(function (e) {
                e.preventDefault();

                var formData = $(this).serialize();

                $.ajax({

                    type: "POST",
                    cache: false,
                    url: "ajax_1.php",
                    data: {myData: formData},

                    success: function (msg) {
                        //alert("Success!");
                        document.getElementById("vanillajs").innerHTML = msg;
                        $("div#jqueryjs").html("<p>" + msg + "</p>");

                    }

                });

            });

        });

    </script>
</head>
<body>
HTML

<form method="POST" action="" id="login">
    <input id="myFirst" type="text" name="myFirst" value=""/>
    <input id="contacted" class="contacted" type="submit" name="contacted" value="Submit it"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

The code below is represents the ajax_1.php which handles the data made from the original page. The code is very limited and although it shows how to handle the data, any production server would need a layer of security built around it so unauthenticated users and web robots would be unable to cause damage.

function PDO_Connect()
{
    $user = 'root';
    $pass = '';
    $PDO = new PDO('mysql:host=localhost;dbname=abook', $user, $pass);
    $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    return $PDO;
}

$PDO = PDO_Connect();

parse_str($_POST['myData'], $myArray);

$first = trim($myArray['myFirst']);
//echo $first;

$command = "SELECT * FROM leads WHERE firstname=TRIM(:first)";
$result = $PDO->prepare($command);
$result->bindParam(':first', $first);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
//print_r($rows);
foreach ($rows as $row) {
    echo "<br/> " . $row['firstname'] . " " . $row['lastname'];
}