Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Then, I have the file update.php with the UPDATE query. The third file is js1.js with AJAX code. If I map the grid.php to update.php through action=update.php, the update query works great. But as soon as I try to include js1.js file to prevent form refreshing, it stops working.

The code is as following:

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:

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

$(function () {

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

        e.preventDefault();

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

    });

});
like image 916
Luke Avatar asked Oct 21 '22 02:10

Luke


1 Answers

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). You can read more about a similar case here: Create a HTML table where each TR is a FORM

  2. Your SQL statement is subject to SQL injection. This is bad. Really, really bad. As I mentioned in the comments, consider changing to MySQLi or PDO and using parameterized queries. You can read more about it here: How can I prevent SQL injection in PHP?

  3. Your HTML code is not clean. 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).
    • There is incomplete inline 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)

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

  1. Wrap the function in a $(document).ready so it is executed when the page finishes loading.
  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).

The final code for js1.js would look like this:

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

    });
});
like image 158
Alvaro Montoro Avatar answered Oct 22 '22 16:10

Alvaro Montoro