Updating a Table with Jquery and Ajax

时间:2022-11-13 17:45:31

I have quite a large page with a lot of content, one part of which is a table of prices against dates. Typically the table looks like this: Updating a Table with Jquery and Ajax

我有一个包含大量内容的大页面,其中一部分是针对日期的价格表。通常情况下,表格如下所示:

The "Previous" and "Next" links and the datepicker enable the user to show a different range of dates in the table. However using simple html forms and php/mysql, the whole page refreshes every time and that looks pretty messy. I want to use jQuery and Ajax to refresh just the table.

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

To that end I have put the table in a separate file using PHP include(). That separate file called calendar_inner.php uses a variable called $startdate to do the necessary mysql queries to get all the data for the table. Now I just need to understand how to feed the included file with a new value of $startdate and then refresh that file. This is where I am groping in the dark with jQuery.

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

Starting with just the datepicker, I have started to write the jQuery script, but unsurprisingly it doesn't work.

从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'
    });
});

Please be gentle with me. My occasional success with jQuery has been limited to occasions when I have been able to copy someone else's piece of code virtually verbatim. Thanks.

请温柔地对待我。我偶尔获得jQuery的成功仅限于我能够逐字复制别人的代码片段。谢谢。

EDIT I've modified my script based on the advice from Raslett but I haven't reached the solution yet.

编辑我根据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);
        }
    });
});

Now the full page doesn't refresh, only the calendar_inner.php file, so that's a little success. I think the issue now is what to do with the result. Using the code above and placing

现在整页不刷新,只有calendar_inner.php文件,所以这有点成功。我认为现在的问题是如何处理结果。使用上面的代码并放置

<div id="getresult"></div>

at the start of calendar_inner.php inserts my 404 Error page into the overall page. Changing html(result) to text(result) writes the whole code of the 404 Error page into the same space. What I don't know is what is being generated by the script that causes the server to invoke the 404 Error page.

在calendar_inner.php的开头,将我的404错误页面插入整个页面。将html(result)更改为text(result)会将404 Error页面的整个代码写入同一空间。我不知道的是脚本生成的是什么导致服务器调用404错误页面。

SECOND EDIT I got rid of the 404 Error. I was calling the url wrong. Now that is corrected, I am getting closer but the remaining stuff to do is pretty mysterious. The script now writes the first row of the table twice: once with a start date of 1 Jan and the second time with the original start date. So now all I have to do is: 1. Persuade the first version of the table row to use the new start date 2. Stop the second version of the table row from showing 3. Pass the start date to the next part of the table where the prices are calculated and written Phew! Not easy.

第二次编辑我摆脱了404错误。我把网址称错了。现在这已经得到纠正,我越来越近了,但剩下要做的事情是非常神秘的。该脚本现在将表的第一行写入两次:一次是开始日期为1月1日,第二次是原始开始日期。所以我现在要做的就是:1。说服表格行的第一个版本使用新的开始日期2.停止显示表格行的第二个版本3.将开始日期传递给表格的下一部分在哪里价格计算和写Phew!不容易。

THIRD EDIT As Rasclatt said, the jQuery is now working and I just need to sort out the calendar_inner.php file. For simplicity, I'm just putting the first few lines below. The key variable is $startdate, which then drives everything else. I need the jQuery to change the value of $startdate.

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

FOURTH EDIT Updated the code of calendar_inner.php and showed more of it. See below.

第四次编辑更新了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>"; 
?>

FIFTH EDIT (!) In reply to Rasclatt, this is what the table looks like after the script has run. Updating a Table with Jquery and Ajax The datepicker, Previous, the checkbox and Next are all in the parent page. The first row of dates starting 30 Sep are the result of the script and the second row of dates are coded into calendar_inner.php. Moving

第五次编辑(!)在回复Rasclatt时,这是脚本运行后表的样子。 datepicker,Previous,复选框和Next都在父页面中。从9月30日开始的第一行日期是脚本的结果,第二行日期编码为calendar_inner.php。移动

<div id="getresult"></div>

further down the page moves the first row of dates accordingly. The code of the form for the datepicker is

在页面下方相应地移动第一行日期。 datepicker的表单代码是

<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>

1 个解决方案

#1


0  

This should load the form, then script which will autoload your table via AJAX into the <div id="get result"></div> container. On submission of the form, it should load into the same spot overwriting the table. So, just to clarify, you wouldn't run any php to build the table on the original load page. All you would run php for is to calculate the $hid, $$ln, and $startdate. Your calendar_inner.php would only contain the calendar code, and the load page would only contain the form and jQuery.

这应该加载表单,然后脚本将通过AJAX将表自动加载到

容器中。在提交表单时,它应该加载到覆盖表的同一位置。所以,只是为了澄清,你不会运行任何PHP来在原始加载页面上构建表。所有你运行php的是计算$ hid,$$ ln和$ startdate。您的calendar_inner.php只包含日历代码,加载页面只包含表单和jQuery。

As an option, I added a preference to the CheckDates(FetchResults) where FetchResults is the name of the container. Just incase you want to load it to a different container name you can.

作为一种选择,我在CheckDates(FetchResults)中添加了一个首选项,其中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>

#1


0  

This should load the form, then script which will autoload your table via AJAX into the <div id="get result"></div> container. On submission of the form, it should load into the same spot overwriting the table. So, just to clarify, you wouldn't run any php to build the table on the original load page. All you would run php for is to calculate the $hid, $$ln, and $startdate. Your calendar_inner.php would only contain the calendar code, and the load page would only contain the form and jQuery.

这应该加载表单,然后脚本将通过AJAX将表自动加载到

容器中。在提交表单时,它应该加载到覆盖表的同一位置。所以,只是为了澄清,你不会运行任何PHP来在原始加载页面上构建表。所有你运行php的是计算$ hid,$$ ln和$ startdate。您的calendar_inner.php只包含日历代码,加载页面只包含表单和jQuery。

As an option, I added a preference to the CheckDates(FetchResults) where FetchResults is the name of the container. Just incase you want to load it to a different container name you can.

作为一种选择,我在CheckDates(FetchResults)中添加了一个首选项,其中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>