Update a record using AJAX without updating

I am trying to update records in a database without updating the form. I have a grid.php page with a form to display and update records. Then I have an update.php file with an UPDATE request. The third file is js1.js with AJAX code. If I map grid.php to update.php via action=update.php , the update request works fine. But as soon as I try to include the js1.js file to prevent the form from updating, it stops working.

The code is as follows:

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'); } }); }); }); 
+5
source share
2 answers

Disclosure: I can sound incredibly patronizing and even keep in mind in my answer, please note that this is not my intention. I will show you how to fix this problem, but let me first add some comments to the above code along with some suggestions:

  • The structure of your HTML is not very good: a form should not wrap every tr , you should use a div instead of a table or a table inside the form inside cell "(the code looks as ugly as it sounds). You can learn more about this case here: Create a table HTML where every TR is FORM

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

  • Your HTML code is not clean. In general, your page will work because the browser will help, but believe me, this is bad programming: you will end up changing the code, forget about it, and it will be a mess. From what I see:

    • There are several elements with the same identifier (all forms created in a loop).
    • There is incomplete inline CSS ( background-color: .
    • Quotes are not available in many places.
    • There are a couple of closures </div> without opening the <div> (it may be OK if the div is opened from header.php, but even if it was, the code will be difficult to maintain)

Finally, the solution. I hope you did not miss the entire text above and jump right here, because it will really help you not only now, but also in the future.

Change these two things and your code will work (as in js1.js):

  • Wrap the function in $(document).ready so that it runs when the page loads.
  • Change the data from $("form").serialize() to $(this).serialize() , so you will only send information from the form with the button you clicked on (instead of all forms).

The final code for js1.js will 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'); } }); }); }); 
+3
source

Okay, so a few things I'm going to try to quickly help you.

Query

Your request is complex, but I feel useless. I have been working with MySQL for a long time, and I can’t remember the situation when I used INNER JOIN in the method that you are. Therefore, a much shorter syntax for your query: SQL Aliases

 $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

Assuming that the HTML in your script is the way you want it to display, here are a few things: you can avoid double quotes so that they don't break your code. I would modify the code inside your loop: Click here to understand the instructions for ".$variable." that I entered into 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

This is a little harder to explain. The jQuery ajax success function can take several parameters that will help you in your request. See this link for more details. Go to the section on the .done() function. One of them is the data returned from the request. This means that in your update4.php file, if you output the data to the browser as a JSON object, you can then use this data on your original page.

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

As another user pointed out in the comments section, your query is very dependent on SQL Injection. Please follow the link they provided to find out more.

Now, if you want all the data to go back, the last set of lines in the update4.php file should be close to:

 <?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 must move these $_POST variables to other variables that you properly sanitized. NEVER assume that your users do not know web technologies. Always, ALWAYS assume that the user is the one who has the malicious intent to steal data from your database. Therefore, ALWAYS check the data entered by the user. The only reason I put this is because you seem to be completely new to these aspects of web development and with all the other information that I presented, I don't want to overload you and disconnect you from web development / design .

Side note

I would suggest looking for a template mechanism of some variety. Generally, it is best to use your display (HTML) and data (PHP) as separately as possible. The only template mechanisms I used earlier were a modified version of the template engine PhpBB 3 and Smarty (on which the phpBB team based its template engine).

From the beginning of entering this text, I saw another answer and quickly read it. I think we both look at slightly different parts of your common problem, so I will give you this entry as a reference, although I think the other user answer is slightly better than mine. I repeat his mood, although if I sound condescending or angry, I do not want to do this.

Also, since I'm sure someone pointed out or told you to get used to using mysqli_ * functions, since mysql_ will be deprecated (no longer in use) in future versions of PHP.

0
source

Source: https://habr.com/ru/post/1200986/


All Articles