weixin_33691700 2017-11-18 22:03 采纳率: 0%
浏览 37

Ajax数据-每个数据

I have a problem with my ajax code... I have a list of checkbox, the idea is insert the data of the marked checkboxes into the database.

If I select only one check box, the insert is correct. But if I select for example 3, all data appears on the same field, as unique value.

This is the example:

HTML

    <input type="checkbox" class="get_value" value="test1">test1</br>
    <input type="checkbox" class="get_value" value="test2">test2</br>
    <input type="checkbox" class="get_value" value="test3">test3</br>
    <input type="checkbox" class="get_value" value="test4">test4</br>
    <input type="checkbox" class="get_value" value="test5">test5</br>
<button type='button' name='submit' id="submit">Submit</button>

This is the ajax code

        <script>
            $(document).ready(function(){
                $('#submit').click(function(){
                    var insert = [];
                    $('.get_value').each(function(){
                        if($(this).is(":checked")){
                            insert.push($(this).val());
                        }
                    });
                    insert = insert.toString();
                    $.ajax({
                        url: "./functions/add_list.php",
                        method: "POST",
                        data:{insert:insert},
                        }
                    });
                });
            });
        </script>

And this one the PHP that do the insert into the database:

if(isset($_POST["insert"])){
    $query = 'INSERT INTO music (name,username) VALUES ("'.$_POST["insert"].'","'.$username.'")';
    $result = mysqli_query($conn, $query);
}

For example if I check "test1" and "test2", I will see in my MySQL "name" field "test1,test2". But I need see them in diferent fields, not in the same.

I have tested the "foreach ($_POST["insert"] as $value) { insert... } but it did not help me.

Someone have an idea about my error?

I appreciate your help so much. Regards,

  • 写回答

1条回答 默认 最新

  • weixin_33682790 2017-11-18 22:11
    关注

    you need to loop on the server side too :

    $arr = explode(',', $_POST["insert"]);
    foreach ($arr as $val) {
              $query = 'INSERT INTO music (name,username) VALUES ("'.$val.'","'.$username.'")';
              $result = mysqli_query($conn, $query);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改