简体   繁体   English

使用AJAX更新记录而不刷新表单

[英]Update record with AJAX without refreshing form

I'm trying to update records in DB without refreshing Form. 我正在尝试更新数据库中的记录而不刷新表单。 I have grid.php page with the form to display and update records. 我有grid.php页面,用于显示和更新记录的表单。 Then, I have the file update.php with the UPDATE query. 然后,我有UPDATE查询的文件update.php The third file is js1.js with AJAX code. 第三个文件是带有AJAX代码的js1.js If I map the grid.php to update.php through action=update.php , the update query works great. 如果我映射grid.phpupdate.php通过action=update.php ,更新询问的伟大工程。 But as soon as I try to include js1.js file to prevent form refreshing, it stops working. 但是一旦我尝试包含js1.js文件以防止表单刷新,它就会停止工作。

The code is as following: 代码如下:

grid.php grid.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="j1.js"></script>
<?php //query.php
    require_once 'header.php';
    if (!$loggedin) die();

    $query = "SELECT SpringMgmt.SpringMgmtID, 
                     SpringMgmt.SpringMgmtActiveYear, 
                     SpringMgmt.PoolID, 
                     SpringMgmt.Notes, 
                     SpringMgmt.SOIEstSubmitted,
                     SpringMgmt.EstAdditional, 
                     SpringMgmt.SOIMeetingScheduled, 
                     Pool.Pool, 
                     Pool.AreaManager, 
                     Employees.EmployeeID, 
                     Employees.FirstName
              FROM SpringMgmt
                   INNER JOIN Pool ON SpringMgmt.PoolID = Pool.PoolID
                   INNER JOIN Employees ON Employees.EmployeeID = Pool.AreaManager ";
    $result = mysql_query($query);
    echo "OK</div>";
    if (!$result) die ("Database access failed0: " . mysql_error());

    //TABLE AND ITS HEADING
    echo '<table id="header" cellpadding="0" cellspacing="0" border="0" >';
    echo "
    <tr> 
    <th>Pool</th>
    <th>Notes</th>
    <th>SO Sent</th>
    <th>Est</th>
    <th>Meet Date</th>
    </tr> 
    ";
    while($record = mysql_fetch_array($result)){
        echo "<form id='myForm' name='myForm'  method=post>";
        echo "<tr>";
        echo "<td >$record[Pool]</td>";
        echo "<td ><textarea size=4 name=Notes rows=3 cols=22>$record[Notes]</textarea> </td>";
        echo "<td style=background-color:><input type=text size=3 name=SOIEstSubmitted value='$record[SOIEstSubmitted]' /></td>";
        echo "<td ><textarea size=4 name=EstAdditional rows=3 cols=12>$record[EstAdditional]</textarea></td>";
        echo "<td style=background-color:><input type=text size=3 name=SOIMeetingScheduled value='$record[SOIMeetingScheduled]' /></td>";
        echo "<td>
              <input type=hidden name='SpringMgmtID' value=$record[SpringMgmtID] />
              <input type=submit name='submit' id='submit' value='Submit' />
              </div></td>";
        echo "</tr>";
        echo "</form>";
    }
    echo "</table>";
?>   

update4.php: update4.php:

<?php 
    require_once 'header.php';
    if (!$loggedin) die();

    if(isset($_POST['submit'])){
        $UpdateQuery = "UPDATE SpringMgmt 
                        SET    Notes='$_POST[Notes]',
                               SOIEstSubmitted='$_POST[SOIEstSubmitted]',
                               EstAdditional='$_POST[EstAdditional]',
                               SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
                        WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
        mysql_query($UpdateQuery);
    };
?>

js1.js js1.js

$(function () {

    $('form').on('submit', function (e) {

        e.preventDefault();

        $.ajax({
            type: 'post',
            url: 'update4.php',
            data: $('form').serialize(),
            success: function () {
                alert('form was submitted');
            }
        });

    });

});

Disclosure: I may sound incredibly patronizing and even mean in my response, please note that it is not my intention. 披露:我可能听起来令人难以置信的光顾,甚至在我的回答中,请注意,这不是我的意图。 I will show you how to fix the issue, but let me first add some comments about the code above along with some suggestions: 我将向您展示如何解决该问题,但让我首先添加一些关于上面代码的评论以及一些建议:

  1. The structure of your HTML is not good: a form shouldn't be wrapping each tr , you should consider using div instead of a table, or a "table inside a form inside a cell" (the code looks as ugly as it sounds). 你的HTML的结构不好:一个form不应该包装每个tr ,你应该考虑使用div而不是表格,或者“在一个单元格内的表格里面”(代码看起来像听起来一样难看) 。 You can read more about a similar case here: Create a HTML table where each TR is a FORM 您可以在此处阅读有关类似案例的更多信息: 创建一个HTML表格,其中每个TR都是一个FORM

  2. Your SQL statement is subject to SQL injection . 您的SQL语句受SQL注入 This is bad. 这不好。 Really, really bad. 真的,非常糟糕。 As I mentioned in the comments, consider changing to MySQLi or PDO and using parameterized queries. 正如我在评论中提到的,考虑更改为MySQLi或PDO并使用参数化查询。 You can read more about it here: How can I prevent SQL injection in PHP? 您可以在此处阅读更多相关信息: 如何在PHP中阻止SQL注入?

  3. Your HTML code is not clean. 您的HTML代码不干净。 In general, your page will work because the browser will help, but trust me, that is bad programming: you'll eventually change the code, forget about it, and it will be a mess. 一般来说,你的页面会起作用,因为浏览器会有所帮助,但请相信我,这是糟糕的编程:你最终会改变代码,忘掉它,这将是一团糟。 From what I see: 从我看到的:

    • There are multiple elements with the same ID (all the forms created by the loop). 有多个元素具有相同的ID(循环创建的所有表单)。
    • There is incomplete inline CSS ( background-color: ). 有不完整的内联CSS( background-color: :)。
    • Quotes are missing in many places. 许多地方缺少行情。
    • There are a couple of closing </div> without an opening <div> (this could be OK if the opening div comes from header.php; but even if that was the case, the code would be difficult to maintain) 有几个没有开头<div>的结束</div> (如果开头div来自header.php,这可能没问题;但即使是这样,代码也很难维护)

Finally, the solution. 最后,解决方案。 I hope you didn't skip all the text above and jump directly here, because it will really help you not only now but in the future. 我希望你没有跳过上面的所有文字并直接跳到这里,因为它不仅会在现在,而且在将来真的会对你有所帮助。

Change these two things and your code will work (both in js1.js): 更改这两件事,您的代码将起作用(均在js1.js中):

  1. Wrap the function in a $(document).ready so it is executed when the page finishes loading. 将函数包装在$(document).ready以便在页面加载完成时执行。
  2. Change the data from $("form").serialize() to $(this).serialize() , this way you will be sending only the information from the form with the button that you clicked on (instead of all the forms). 将数据从$("form").serialize()更改$(this).serialize() ,这样您将只使用您单击的按钮(而不是所有表单)从表单发送信息。

The final code for js1.js would look like this: js1.js的最终代码如下所示:

$(document).ready(function () {

    $('form').on('submit', function (e) {

        e.preventDefault();
        $.ajax({
            type: 'post',
            url: 'update4.php',
            data: $(this).serialize(),
            success: function () {
                alert('form was submitted');
            }
        });

    });
});

Okay, so a few things I'm going to try and help you out with quickly. 好的,我将尝试一些快速帮助你的事情。

Query 询问

Your query is complicated, but I feel needlessly so. 你的查询很复杂,但我觉得不必要。 I've been doing things with MySQL for quite some time now and I can't recall a situation where I used INNER JOIN in the method you are. 我已经用MySQL做了很长一段时间了,我不记得我在你的方法中使用INNER JOIN的情况。 A much shorter syntax for your query would therefore be: SQL Aliases 因此,查询的语法要短得多: SQL别名

$query = "SELECT s.*, p.Pool, p.AreaManager, e.EmployeeID, e.FirstName
              FROM SpringMgmt as s, Pool as P, Employees as E
              WHERE s.PoolID = p.PoolID AND e.EmployeeID = p.AreaManager ";

HTML HTML

Assuming the HTML in your script is the way you want for it to be shown, here's a few things: you can escape double quotes so that they do not break your code. 假设您的脚本中的HTML是您希望显示它的方式,这里有一些事情:您可以转义双引号,这样它们就不会破坏您的代码。 I would change the code inside your loop to this: Click Here to understand the ".$variable." 我会将循环中的代码更改为: 单击此处以了解".$variable." statements I put in your code 我在你的代码中添加的语句

echo "<form id=\"myForm\" name=\"myForm\"  method=\"post\">";
        echo "<tr>";
        echo "<td data-field-id=\"pool\">".$record['Pool']."</td>";
        echo "<td ><textarea data-field-id=\"notes\" size=\"4\" name=\"Notes\" rows=\"3\" cols=\"22\">".$record['Notes']."</textarea> </td>";
        echo "<td style=\"background-color:\"><input data-field-id=\"submitted\" type=\"text\" size=\"3\" name=\"SOIEstSubmitted\" value=\"".$record['SOIEstSubmitted']."\" /></td>";
        echo "<td ><textarea size=\"4\" data-field-id=\"additional\" name=\"EstAdditional\" rows=3 cols=\"12\">".$record['EstAdditional']."</textarea></td>";
        echo "<td style=\"background-color:\"><input data-field-id=\"meetingScheduled\" type=\"text\" size=\"3\" name=\"SOIMeetingScheduled\" value=\"".$record['SOIMeetingScheduled']."\" /></td>";
        echo "<td>
              <input type=\"hidden\" name=\"SpringMgmtID\" value=\"$record[SpringMgmtID]\" />
              <input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\" />
              </div></td>";
        echo "</tr>";
        echo "</form>";

AJAX/Javascript Calls AJAX / Javascript调用

This is a bit more complicated to explain. 解释起来有点复杂。 The jQuery ajax object success function can accept a few parameters to help you in your request. jQuery ajax对象success函数可以接受一些参数来帮助您处理请求。 See this link for more explanation. 有关更多说明,请参阅此链接 Jump the section about the .done() function. 跳转关于.done()函数的部分。 One of them is the data returned FROM the request. 其中之一是从请求返回的数据。 This means that in your update4.php file, if you would output the data to the browser as a JSON object, you could then use that data back on your original page. 这意味着在update4.php文件中,如果要将数据作为JSON对象输出到浏览器,则可以在原始页面上使用该数据。

$(document).ready(function(){
$('form').on('submit', function (e) {
    e.preventDefault();

    $.ajax({
        type: 'post',
        url: 'update4.php',
        data: $(this).serialize(),
        success: function (data,successText) {
           for(var x in data){
              //Use tree traversing to find the input/text elements that have the data-field-id option equal to the x variable; I can't test it right now so I don't want to have this here.
           }
        }
    });

});

}); });

Update4.php Update4.php

As another user pointed out in the comment section, your query here is very prone to SQL Injection. 正如另一位用户在评论部分指出的那样,您的查询非常容易出现SQL注入。 Please follow the link they provided to read more. 请按照他们提供的链接阅读更多信息。

Now, assuming you want all of the data returned back, the very last set of lines in your update4.php file should be something close to : 现在,假设您想要返回所有返回的数据,update4.php文件中的最后一行应该接近:

<?php 
  require_once 'header.php';
    if (!$loggedin) die();

    if(isset($_POST['submit'])){
        $UpdateQuery = /*"UPDATE SpringMgmt 
                        SET    Notes='$_POST[Notes]',
                               SOIEstSubmitted='$_POST[SOIEstSubmitted]',
                               EstAdditional='$_POST[EstAdditional]',
                               SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
                        WHERE SpringMgmtID='$_POST[SpringMgmtID]'"; 
               Don't do this, please use a prepared statement or mysql(i)_real_escape_string() on the data.*/
        $result = mysql_query($UpdateQuery);
        if($result!==false){
              echo json_encode(array(
                     'notes'=> $_POST['Notes'],
                     'submitted'=> $_POST['SOIEstSubmitted'],
                     'additional'=>$_POST['EstAdditional'],
                     'meetingScheduled'=>$_POST['SOIMeetingScheduled']
                  ));
        }
    };

NOTE I do NOT recommend doing this. 注意建议这样做。 You should move these $_POST variables into other variables that you have properly sanitized. 您应该将这些$_POST变量移动到已正确清理的其他变量中。 NEVER assume that your users have no knowledge of web technologies. 绝不假设您的用户不了解Web技术。 Always, ALWAYS assume the user is someone who has the malicious intent to steal the data from your database. 始终, 始终假定用户是恶意企图窃取数据库中数据的人。 Therefore, ALWAYS check user-inputted data. 因此,始终检查用户输入的数据。 The only reason I have set this up is because you seem like you are fairly new to these aspects of web development and with all of the other information I've presented I don't want to overload you and turn you off from web development/design. 我设置这个的唯一原因是因为你似乎对网络开发的这些方面相当新,并且我提供的所有其他信息我不想让你超负荷并让你从网络开发中脱身/设计。

Side Note 边注

I would suggest looking up a template engine of some variety. 我建议查找一些类型的模板引擎。 It is generally a better practice to have your display (HTML) and data (PHP) as separate as possible. 将显示(HTML)和数据(PHP)尽可能分开通常是一种更好的做法。 The only template engines I've used previously were a modified version of PhpBB 3's template engine, and Smarty (which the phpBB team based their template engine on). 我之前使用的唯一模板引擎是PhpBB 3模板引擎的修改版本,以及Smarty(phpBB团队基于其模板引擎)。

Since beginning to type this I've seen another answer posted and read it quickly. 从开始输入这个我已经看到另一个答案发布并快速阅读。 I think both of us address slightly different portions of your overall problem, so I will give this post to you as a reference, though I think the other user's answer is a bit better than mine is. 我想我们两个都解决了你整体问题的不同部分,所以我会把这篇文章作为参考给你,虽然我认为其他用户的答案比我的好一点。 I repeat his sentiment though, if I sound condescending or mean, I don't mean to. 我重复他的观点,如果我听起来居高临下或卑鄙,我不是故意的。

Also, as I'm sure someone will or has pointed out to you, get in the habit of using mysqli_* functions as mysql_ will be deprecated (no longer usable) in coming versions of PHP. 另外,由于我确信有人会或已经向你指出,养成使用mysqli_ *函数的习惯,因为在即将推出的PHP版本中将不推荐使用mysql_(不再可用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM