将数组js变量传递给php

时间:2015-11-06 08:52:21

标签: javascript php jquery ajax

目前我已将变量存储在Javascript数组中。这里的目标是将它们变成PHP变量,以便我可以使用这些变量并将它们插入到我的数据库中。

此代码的问题是AJAX部分不起作用。请让我朝着正确的方向前进,因为我是AJAX的新手。我确实尝试了解它们但仍然不太了解。无需刷新页面即可完成此操作。欢迎使用AJAX以外的方法。

这是我目前的代码:

<button onclick="Bookings()">Book</button>
<script>
    function Bookings() {
        var t2Cells = document.getElementsByClassName("t2");
        for (var i = 0; i < t2Cells.length; i++) {
            var t2CellsIndex [i] = t2Cells[i].cellIndex
            var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
            //alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
            var tbl = document.getElementById("tblMain");
            //alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
            var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
            var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML

            $.ajax({
                type: "POST",
                url: 'bookingconfirm.php',
                data: "studioSelected=" + studioSelect,
                success: function(data) {
                    alert("success!");
                }
            });
        }
    }
</script>

<?php 
    //bookingconfirmed.php
    if (isset($_POST['studioSelect'])) {
        $uid = $_POST['studioSelect'];
        //steps to insert into database.

1 个答案:

答案 0 :(得分:1)

首先,你应该在foreach之外移动ajax调用

var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
    var t2CellsIndex [i] = t2Cells[i].cellIndex
    var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
    //alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
    var tbl = document.getElementById("tblMain");
    //alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
    var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML

    // add data to array
    usefulData.push(studioSelected);

    var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}

        $.ajax({
            type: "POST",
            url: 'bookingconfirm.php',
            data: {'usefuldata': usefulData},
            success: function(data) {
                alert("success!");
            }
        });

然后在你的php文件中:

if (isset($_POST['usefuldata'])) {
    var_dump($_POST['usefuldata']);
}