How to pass list variables from jQuery to POST method PHP

时间:2017-07-12 08:10:08

标签: php jquery pdo

I have a list box with some values, after selecting the value from list box I want to concatenate them with ':' and pass it to POST method so that I can insert the list items into a database table.

But I am not sure how to achieve this, I will be really thankful for any suggestions.

<!doctype html>
<html lang="en">

<head>

    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>

    <select class="sweet" name="sweets" multiple="multiple">
        <option>Chocolate</option>
        <option>Candy</option>
        <option>Taffy</option>
        <option>Caramel</option>
        <option>Fudge</option>
        <option>Cookie</option>
    </select>
    <input type="submit" name="submit" value="submit" />
    <script>
        $(function() {
            var s_type = "";
            $('.sweet').click(function() {
                var selected = $(this).val();
                if (s_type.length) {
                    s_type += " : " + $(this).val();
                } else {
                    s_type += $(this).val();
                }
                $.post('new_page.php', 'sweet=' + s_type, function(response) {
                    alert(response);
                });

            });
        });
    </script>
</body>

</html>

Php Script

 <?php
    $value = $_POST['sweet'];
    echo "I got your value! " .$value;
    if(isset($_POST['submit']))
    {   
        $db =  new PDO("sqlite:c:/sqlite/test.db");
        $q1 = $db->prepare('INSERT INTO test_sweet(sweets) values(?)');
        $q1->execute(array($value));
        echo '*****profile_coll' .$value;
    }
?>

1 个答案:

答案 0 :(得分:0)

Try like this

$(function()
        { 
            var s_type="";
            $('.sweet').click(function()
                {
                    s_type = $(this).val() ? $(this).val().join(":") : "";
                    $.post('new_page.php', 'sweet=' +s_type, function (response) 
                    {
                        alert(response);
                    });
                });

        });