Php 使用Jquery和Ajax更新表

Php 使用Jquery和Ajax更新表,php,jquery,mysql,ajax,Php,Jquery,Mysql,Ajax,我有一个相当大的页面,里面有很多内容,其中一部分是一个日期价格表。该表通常如下所示: “上一个”和“下一个”链接以及日期选择器允许用户在表中显示不同的日期范围。然而,使用简单的html表单和php/mysql,整个页面每次都会刷新,看起来相当混乱。我想使用jQuery和Ajax来刷新表 为此,我使用PHP include将表放在一个单独的文件中。名为calendar_inner.php的单独文件使用名为$startdate的变量执行必要的mysql查询,以获取表的所有数据。现在我只需要了解如何

我有一个相当大的页面,里面有很多内容,其中一部分是一个日期价格表。该表通常如下所示:

“上一个”和“下一个”链接以及日期选择器允许用户在表中显示不同的日期范围。然而,使用简单的html表单和php/mysql,整个页面每次都会刷新,看起来相当混乱。我想使用jQuery和Ajax来刷新表

为此,我使用PHP include将表放在一个单独的文件中。名为calendar_inner.php的单独文件使用名为$startdate的变量执行必要的mysql查询,以获取表的所有数据。现在我只需要了解如何使用$startdate的新值来填充包含的文件,然后刷新该文件。这就是我用jQuery在黑暗中摸索的地方

从datepicker开始,我已经开始编写jQuery脚本,但毫不奇怪它不起作用

$('#StartDateCal').on('submit', function(g) { 
    g.preventDefault();  //prevent form from submitting
    var startdate = $("#StartDate").val();
    $.ajax ({
        type: 'post',
        url: 'calendar_inner.php',
        data: data,
        dataType: 'text'
    });
});
请对我温柔一点。我偶尔在jQuery方面取得的成功仅限于我能够几乎一字不差地复制别人的代码的情况。谢谢

编辑 我已经根据Raslett的建议修改了脚本,但还没有找到解决方案

$('#StartDateCal').on('submit', function(g) { 
    g.preventDefault();  //prevent form from submitting
    $.ajax ({
        type: 'post',
        url: 'calendar_inner.php',
        data: $('#StartDateCal').serialize(),
        success: function(result) {
            $('#getresult').html(result);
        }
    });
});
现在整个页面不刷新,只刷新calendar_inner.php文件,所以这有点成功。我认为现在的问题是如何处理结果。使用上面的代码并放置

<div id="getresult"></div>
在calendar_inner.php的开头,将我的404错误页面插入到整个页面中。将htmlresult更改为textresult会将404错误页面的整个代码写入同一个空间。我不知道脚本生成了什么,导致服务器调用404错误页面

第二次编辑 我排除了404错误。我打错网址了。现在这是正确的,我越来越接近,但剩下的事情是相当神秘的。现在,脚本会将表的第一行写入两次:一次是开始日期为1月1日,第二次是原始开始日期。所以现在我要做的就是: 1.说服表行的第一个版本使用新的开始日期 2.停止显示表格行的第二个版本 3.将开始日期传递到表的下一部分,在该部分计算并写入价格 呸!不容易

第三次编辑 正如Rasclatt所说,jQuery现在正在工作,我只需要整理calendar_inner.php文件。为了简单起见,我只在下面放上前几行。关键变量是$startdate,它将驱动所有其他变量。我需要jQuery来更改$startdate的值

第四版 更新了calendar_inner.php的代码并显示了更多内容。见下文

<div id="getresult"></div>
<script>
$(document).ready(function() {
//Submit change of date in price tab without refreshing page
$('#StartDateCal').on('submit', function(g) { 
        g.preventDefault();  //prevent form from submitting
        $.ajax ({
            type: 'post',
            url: '/includes/calendar_inner.php',
            data: $('#StartDateCal').serialize(),
            success: function(result) {
                console.log(result),
                $('#getresult').html(result);
            }
        });
    });
});
</script>
<?php
if(isset($_POST['StartDate']) && !empty($_POST['StartDate'])) {
            $startdate  =   htmlentities($_POST['StartDate'], ENT_QUOTES);
            $firstdate  =   date('Y-m-d',$startdate);
            $lastdate   =   date('Y-m-d',strtotime('+11 days',strtotime($firstdate)));

            // database insertion of above variables
        }else{
            $firstdate = date('Y-m-d',$startdate);
$lastdate = date('Y-m-d',strtotime('+11 days',strtotime($firstdate)));
        }

//Select database
require_once('../Connections/MySQL.php');
mysql_select_db($database_MySQL, $MySQL);
mysql_set_charset("utf8");

// Create a temporary table
$query_temptable = "CREATE TEMPORARY TABLE temptable (dt DATE NOT NULL)";
$result = mysql_query($query_temptable, $MySQL) or die(mysql_error());

//Now loop through the date range and fill the temporary table
$thisdate = $firstdate;
while (strtotime($thisdate) <= strtotime($lastdate)){
$query_insertdate = "INSERT INTO temptable (dt) VALUES ('$thisdate')";
$result2 = mysql_query($query_insertdate, $MySQL) or die(mysql_error());
$thisdate = date('Y-m-d', strtotime('+1 day', strtotime($thisdate)));
}

// MySQL query to get price_id (or blank) for all dates in range
$query_tariff = "SELECT temptable.dt, lh_dates.tariff_id FROM temptable LEFT JOIN lh_dates ON temptable.dt = lh_dates.dt AND hid = '$hid'";
$tariff = mysql_query($query_tariff, $MySQL) or die(mysql_error());

// Create array of tariff_ids
$i = 0;
$tariff_id_list = array();
while ($row_tariff = mysql_fetch_assoc($tariff)) {
$tariff_id_list[$i] = $row_tariff['tariff_id'];
$date_list[$i] = $row_tariff['dt'];
$i++;
}
$tariff_id_unique = array_unique($tariff_id_list);

// Drop the temporary table
$query_droptable = "DROP TEMPORARY TABLE IF EXISTS temptable";
$result3 = mysql_query($query_droptable, $MySQL) or die(mysql_error());

//Here we start building the pseudo-table using divs 
echo "<div class='calendar'>";
// Dates row
echo "<div class='toprow'>"; 
echo "<div class='cal_firstcol'>&nbsp;</div>";
$i = 0;
$thisdate=strtotime($firstdate);
while ($i++ < 12) {
$day_week = date('D', $thisdate); 
$day_num = date('j', $thisdate);
$month_name = strtoupper(date('M', $thisdate));
echo "<div class='cal_dates'>";
echo $day_week."<br><span class='cal_day'>".$day_num."</span><br>".$month_name;
$thisdate = $thisdate+86400;
echo "</div>"; 
}
echo "<div class='clear'></div></div>";

// Room rows
//MySQL query to get rooms
$query_room = "SELECT room_id, roomtype, normalocc, singleocc, extrabed, childbed, cot FROM lh_rooms WHERE hid = '$hid' ORDER BY orderr ASC";
$room = mysql_query($query_room, $MySQL) or die(mysql_error());
while ($row_room = mysql_fetch_assoc($room)) {
foreach ($tariff_id_unique as $value) {
$tariff_id = $value;
$room_id = $row_room['room_id'];
$query_price = "SELECT * FROM lh_prices WHERE tariff_id = '$tariff_id' AND room_id = '$room_id'";
$price = mysql_query($query_price, $MySQL) or die(mysql_error());
$row_price[$value] = mysql_fetch_assoc($price);
}

echo "<div class='row'>"; 
echo "<div class='cal_firstcol'>".$row_room['roomtype']."</div>";
$thisdate = $firstdate;
$i=0;
while (strtotime($thisdate) <= strtotime($lastdate)){
$thisday = strtolower(date('D',strtotime($thisdate)));
echo "<div class='cal_pricecol'>";
if (in_array($thisday, $we_rates)) {
echo $row_price[$tariff_id_list[$i]]['price_we_std'];   
}else{
echo $row_price[$tariff_id_list[$i]]['price_wd_std'];
}
echo "</div>";
$i++;
$thisdate = date('Y-m-d',strtotime('+1 day',strtotime($thisdate)));
}
echo "</div>";

if (($row_room['extrabed']>=1)||($row_room['childbed']>=1)) {
echo "<div class='row hiddenrow' style='display:none'>"; 
echo "<div class='cal_firstcol'>Child Extra Bed</div>";
$thisdate = $firstdate;
$i=0;
while (strtotime($thisdate) <= strtotime($lastdate)){
$thisday = strtolower(date('D',strtotime($thisdate)));
echo "<div class='cal_pricecol'>";
echo $row_price[$tariff_id_list[$i]]['price_eb_c']; 
echo "</div>";
$i++;
$thisdate = date('Y-m-d',strtotime('+1 day',strtotime($thisdate)));
}
echo "<div class='clear'></div></div>";
}

}

echo "</div>"; 
?>
第五次编辑! 作为对Rasclatt的回复,这是脚本运行后表的外观。 日期选择器、上一个、复选框和下一个都在父页面中。从9月30日开始的第一行日期是脚本的结果,第二行日期编码为calendar_inner.php。移动的

<div id="getresult"></div>
页面再向下移动第一行日期。 日期选择器的表单代码为

<form id="StartDateCal">
<input type="hidden" name="hid" id="hid" value="<?php echo $hid ?>">
<input type="hidden" name="lang" id="lang" value="<?php echo $$ln ?>">
From <input name="StartDate" id="StartDate" class="datebox" size="10" value="<?php echo date('j M Y', $startdate) ?>" type="date"> 
<input name="submit" class="button" id="CalSubmitBtn" type="submit" value="Go">
</form>

这将加载表单,然后加载脚本,脚本将通过AJAX自动将表加载到容器中。提交表格时,应将其加载到同一位置,覆盖表格。因此,澄清一下,您不会运行任何php在原始加载页面上构建表。运行php的目的就是计算$hid、$$ln和$startdate。您的calendar_inner.php将只包含日历代码,而加载页面将只包含表单和jQuery

作为一个选项,我向CheckDatesFetchResults添加了一个首选项,其中FetchResults是容器的名称。如果您想将其加载到不同的容器名称,您可以

<form id="StartDateCal">
<input type="hidden" name="hid" id="hid" value="<?php echo $hid ?>">
<input type="hidden" name="lang" id="lang" value="<?php echo $$ln ?>">
From <input name="StartDate" id="StartDate" class="datebox" size="10" value="<?php echo date('j M Y', $startdate) ?>" type="date"> 
<input name="submit" class="button" id="CalSubmitBtn" type="submit" value="Go">
</form>
<div id="getresult"></div>
<script>
    function CheckDates(FetchResults)
        {
             $.ajax ({
                type: 'post',
                url: '/includes/calendar_inner.php',
                data: $("#StartDateCal").serialize(),
                success: function(result) {
                 $("#"+FetchResults).html(result);
                }
            });
        }
    $(document).ready(function() {
        // Auto load ajax
        CheckDates('getresult');
        // On submit load ajax
        $('#StartDateCal').submit(function() {
            // Add a loader image or text so you know it's refreshing
            $('#getresult').html("Loading...");
            // Run table loader
            CheckDates('getresult');
            return false;
        });
    });
</script>

是的,表格是id=StarteDateCal。我没有使用serialize,因为当我只传递一个变量时,我认为它是不必要的。然而,我的代码中有一个小小的手指错误,因为数据应该是startdate。我已经在使用您建议的代码方面取得了一些进展,但还没有。更多信息,请参阅我对原始帖子的编辑。不,今天不是真的这么说。也许我应该说它等于时间。我知道您的calendar_inner.php代码来自何方,但目前还不太清楚。我意识到datepicker的名称和id为StartDate,因此我更改了您的$\u POST变量以适应此情况。然而,当我使用datepicker更改startdate时,我仍然得到两行日期:第一行从1月1日开始,第二行从今天的10月1日开始。我将用更多的calendar_inner.php代码对我的原始问题进行另一次编辑。我现在从console.log中发现,结果包含div、脚本和表的第一行以及新日期。这就解释了为什么我会得到两行日期:第一行是新的o
然后是旧的。我怎样才能在结果中得到$startdate的一个新值呢?Rasclatt,我刚刚添加了一个可视化的表,因为它在运行脚本后会看到它,还有表单的代码。我不确定你想看哪个。我真的很感激你在这件事上能耐心地支持我。让我们一起来。而且,我加入代码的唯一原因是向你展示反馈。您可以将反馈指向任何容器。谢谢Rasclatt。我现在就把calendar_inner.php放进去。最初$startdate在父文件中设置为今天。然后表单通过jQuery发送一个新值,该值需要传递到$startdate。您是否考虑过使用许多优秀的基于jQuery的表数据插件中的一个来为您处理客户端部分?Mike Brant。不,我没有考虑过插件。我刚看了一些,但没有看到任何能满足我要求的。也许有一些更全面的方法可以做到,但这需要时间去发现,更多的时间来设置ip,然后我会得到很多没有被使用的代码。