Post jQuery with PHP

Hello All,

I have the following jQuery script that I would like to post to my mysql database with php. How would I go about getting this information to post to the database? Here is what I have so far.

Thank you in advance.

<script>
        $(document).ready(function () {

            //we want to intialze the values
            values = {};
            values['vehicle'] = "car";
            values['gender'] = "male";
            values['age'] = "25";
            values['position'] = "manager";

            //we need to handle the image clicks
            $("#car, #bus, #train, #boat, #plane, #man, #woman, #25, #35, #45, #55, #manager, #director, #president, #CXO").click(function (event) {
                event.preventDefault();

                //we want to know what row we are dealing with
                var imageclass = $(this).attr('class');

                //we need all of the other images in the row turned to not selected
                $("." + imageclass).each(function() {
                    if ($(this).id != event.target.id)
                    {
                        var src = $(this).attr('src');
                        if (src.indexOf("2") >= 0)
                        {
                            $(this).attr('src', src.replace("2.png", ".png"));
                        }
                    }
                });

                setImageAsSelected(event.target.id);
            });

            function setImageAsSelected(id) {
                var current = $("#" + id).attr('src');
                var next;
                if (current.indexOf("2") < 0) {
                    next = current.replace(".png", "2.png");
                }
                $("#" + id).attr('src', next);
                values[$("#" + id).attr('class')] = id;
            }

            //we need to handle the go click
            $("#go").click(function () {
                var sql = "INSERT INTO TABLE (Vehicle, Gender, Age, Positon) VALUES ('" + values['vehicle'] + "', '" + values['gender'] + "', '" + values['age'] + "','" + values['position'] + "');";
                alert(sql);
            });

        });

    </script>

Hi mrbambrick, welcome to the forums!

First off, you really don’t want to be executing SQL that’s submitted via POST or GET, as that’s a big security risk! It’s much better (and more efficient) just to submit the necessary values and then construct the query server-side.

Your click handler could look something like this:

$("#go").click(function () {
    $.ajax({
        type: "POST",
        url: '/save.php',
        data: values,
        success: function() {
            console.log('Data saved to server');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
});

then, in your PHP script (which I’ve imaginatively named save.php) you can do something along these lines:


// Sanitize input to remove script tags etc.
$vehicle  = filter_input(INPUT_POST, 'vehicle', FILTER_SANITIZE_STRING);
$gender   = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
$age      = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
$position = filter_input(INPUT_POST, 'position', FILTER_SANITIZE_STRING);

// Try to execute the query using a prepared statement to protect against SQL injection
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare('INSERT INTO MyTable (Vehicle, Gender, Age, Positon) VALUES (:vehicle, :gender, :age, :position)');
    $stmt->execute(array(
        ':vehicle'  => $vehicle,
        ':gender'   => $gender,
        ':age'      => $age ,
        ':position' => $position
    ));
    $dbh = null;
} catch (PDOException $e) {
    // Return an error header and a message, so the JS can respond accordingly
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    echo "Error: " . $e->getMessage();
    die();
}

fretburner,

Thank you much for the welcome and all of your help. I will try implement this and see where it takes me. I am a newbie to PHP.

Mike

The issue I am having now is that the images are not clicking and the ‘go’ button is not clicking. Here is the html doc in it’s entirety:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Bambrino's</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <style>
        img
        {
            cursor: pointer;
        }
    </style>
</head>
<body>
       <table align="center" width="480" border="0">
        <tr>
            <td>
                <img id="car" src="b_car.png" class="vehicle" />
            </td>
            <td>
                <img id="bus" src="b_bus.png" class="vehicle" />
            </td>
            <td>
                <img id="train" src="b_train.png" class="vehicle" />
            </td>
            <td>
                <img id="boat" src="b_boat.png" class="vehicle" />
            </td>
            <td>
                <img id="plane" src="b_plane.png" class="vehicle" />
            </td>
        </tr>
    </table>
    <br  />
    <table align="center" width="142" border="0">
        <tr>
            <td width="134"">
                <img id="man" src="b_man.png" width="27" height="70" class="gender" />

            </td>
            <td width="123">
                <img id="woman" src="b_woman.png" width="32" height="70" class="gender" />
            </td>
        </tr>
    </table>
    <br  />
    <table align="center" width="480" border="0">
        <tr>
            <td align="center">
                <img id="25" src="twentyfive.png" width="106" height="39" class="age" />
            </td>
            <td align="center">
                <img id="35" src="thirtyfive.png" width="106" height="39" class="age" />
            </td>
            <td align="center">
                <img id="45" src="fourtyfive.png" width="106" height="39" class="age" />
            </td>
            <td align="center">
                <img id="55" src="fiftyfive.png" width="106" height="39" class="age" />
            </td>
        </tr>
    </table>
    <br />
    <table align="center" width="480" border="0">
        <tr>
            <td align="center">
                <img id="manager" src="manager.png" width="106" height="39" class="position" />
            </td>
            <td align="center">
                <img id="director" src="director.png" width="106" height="39" class="position" />
            </td>
            <td align="center">
                <img id="president" src="president.png" width="106" height="39" class="position" />
            </td>
            <td align="center">
                <img id="CXO" src="CXO.png" width="106" height="39" class="position">
            </td>
        </tr>
    </table>
    <center><button type="button" id="go">Go</button></center>

    <script>
        $(document).ready(function () {

            //we want to intialze the values
            values = {};
            values['vehicle'] = "car";
            values['gender'] = "male";
            values['age'] = "25";
            values['position'] = "manager";

            //we need to handle the image clicks
            $("#car, #bus, #train, #boat, #plane, #man, #woman, #25, #35, #45, #55, #manager, #director, #president, #CXO").click(function (event) {
                event.preventDefault();

                //we want to know what row we are dealing with
                var imageclass = $(this).attr('class');

                //we need all of the other images in the row turned to not selected
                $("." + imageclass).each(function() {
                    if ($(this).id != event.target.id)
                    {
                        var src = $(this).attr('src');
                        if (src.indexOf("2") >= 0)
                        {
                            $(this).attr('src', src.replace("2.png", ".png"));
                        }
                    }
                });

                setImageAsSelected(event.target.id);
            });

            function setImageAsSelected(id) {
                var current = $("#" + id).attr('src');
                var next;
                if (current.indexOf("2") < 0) {
                    next = current.replace(".png", "2.png");
                }
                $("#" + id).attr('src', next);
                values[$("#" + id).attr('class')] = id;
            }

            //we need to handle the go click
$("#go").click(function () {
    $.ajax({
        type: "POST",
        url: 'test/insert.php',
        data: values,
        success: function() {
            console.log('Data saved to server');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
});

    </script>


</body>
</html>

You’ve got a couple of typos in your code.

There’s an extra double quote here, om the TD width attribute:

<td width="134"">
                <img id="man" src="b_man.png" width="27" height="70" class="gender" />

and you’re missing the closing }); at the end of your JS. In reality, you don’t actually need to wrap your JS in $(document).ready(function () {}), as long as you place your script just before the closing </body> tag it’ll only be executed once the page content is loaded anyway.

I really appreciate you taking the time. We are getting closer.

The buttons are working but the ‘go’ button is still not working. Here is where we are with the script:

<script>

            //we want to intialze the values
            values = {};
            values['vehicle'] = "car";
            values['gender'] = "male";
            values['age'] = "25";
            values['position'] = "manager";

            //we need to handle the image clicks
            $("#car, #bus, #train, #boat, #plane, #man, #woman, #25, #35, #45, #55, #manager, #director, #president, #CXO").click(function (event) {
                event.preventDefault();

                //we want to know what row we are dealing with
                var imageclass = $(this).attr('class');

                //we need all of the other images in the row turned to not selected
                $("." + imageclass).each(function() {
                    if ($(this).id != event.target.id)
                    {
                        var src = $(this).attr('src');
                        if (src.indexOf("2") >= 0)
                        {
                            $(this).attr('src', src.replace("2.png", ".png"));
                        }
                    }
                });

                setImageAsSelected(event.target.id);
            });

            function setImageAsSelected(id) {
                var current = $("#" + id).attr('src');
                var next;
                if (current.indexOf("2") < 0) {
                    next = current.replace(".png", "2.png");
                }
                $("#" + id).attr('src', next);
                values[$("#" + id).attr('class')] = id;
            }

            //we need to handle the go click
$("#go").click(function () {
    $.ajax({
        type: "POST",
        url: 'insert.php',
        data: values,
        success: function() {
            console.log('Data saved to server');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
});


    </script>

Try opening your browser’s console and seeing if you get any errors returned. Most browsers should allow you to see the POST request that is being made to the server (under the ‘Network’ tab on Chrome) and see if the there is any problem calling the PHP script.