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');
}
});
});
});
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:
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
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?
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):
Wrap the function in a $(document).ready so it is executed when the page finishes loading.
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');
}
});
});
});
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. A much shorter syntax for your query would therefore be: 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 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. I would change the code inside your loop to this: Click Here to understand the ".$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
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. See this link for more explanation. Jump the section about the .done() function. 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.
$(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 comment section, your query here is very prone to SQL Injection. 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 :
<?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. NEVER assume that your users have no knowledge of web technologies. 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. 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).
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.
Related
I created an HTML table with PHP as follows:
$i = 1;
while($row = mysql_fetch_array($result)){
Print "<tr>";
Print "<td><input id='prEff[$i]' type='number' step='0.01' min='0.01' max='0.99' value='.85' </td>";
Print "<td>".$row['ErdEfficiency'] . "</td>";
Print "<td>".$row['TheoreticalSEC'] . "</td></tr>";
$i++;
}
The input cell has a jquery.change function that is called when the number is changed within the range. During debugging, clicking the up or down button once (in chrome) causes the input to run through all values until the upper or lower limit is reached. So the function is called, but only after the whole range of values is run through.
If the page is refreshed without debugging, the jquery is called, but the button sticks since it is experiencing the bug as described.
Here is the simple jquery function:
$('[id^="prEff["]').change(function (){
var test = this;
alert("hi");
});
Its been a difficult bug to track, and I'm not sure what is causing it. It has occurred with an onchange attribute in the input, as well as a javascript eventListener, and jquery change. It may be the way the PHP is printing the input but I've tried a couple different ways without success.
It seems like you have an unclosed <input> tag in your code. Make sure you close it and you should be fine:
Print "<td><input id='prEff[$i]' type='number' step='0.01' min='0.01' max='0.99' value='.85' /> </td>";
I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?
I also guess that i should use some Jquery stuff to make the content editable :P ?
The list is being looped like this:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo $products['product_name'];
echo 'Edit me';
}
As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/
These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.
Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?
The list/forms:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo "<span>" . $products['product_name'] . "</span>";
echo "<a class='editButton'>Edit</a>";
echo "<form action='products.php' method='post' style='display: none;'>
<input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
<input type='text' name='title' value='" . $products['product_name'] . "' >
<input type='submit' value='Update' >
</form>";
echo "<br/>";
}
The jQuery:
$(".editButton").click(function(){
//Hide the text entry and the edit link
$(this).prev().hide();
$(this).hide();
//Show the form
$(this).next().show();
});
If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.
I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);
Hi i want to get changed text value from JQuery but i can't select edit text with JQUERY because edit texts generated from php while loop that this php code query on database and get value of edit texts and in my program i have edit button for every edit texts and when the user changed value of edit text i select new value and when user click edit button send this value from get method to another php page with jquery $.ajax function and send new value to that php code with ajax.But i don't know how can i select edit text that it's value changed because i don't know id of that edit text!.And when i set one id for every edit text i only get first edit text value from $("#id").change().val();.I use below code but it doesn't work.I am beginner in java script and don't know how fix this problem!.
var testAnswer;
function setNewTestAnswer(id){
testAnswer = $("#id").val();
}
function sendToEdit(pID,phID,thDate,type){
var info = 'pId='+pID+'&phId='+phID+'&testAnswer='+testAnswer+'&thDate='+thDate+'&type='+type;
}
2nd function use testAnswer that user changed in edit text.
php code
<?php
include 'Connect.php';
if(match($_POST['pId'], "/^[\d]+$/") ){
$pId = $_POST['pId'];
$result = mysql_query("select pName, pID, phName, phID, testHistoryDate, type, testAnswer from patient join reception using(pID) join physician using(phID) join testHistory using(rID) join test using(tID) where pID = $pId",$connection);
}
else
die("Insert true value");
while($row=mysql_fetch_array($result)){
echo "<tr><td>";
echo $row["pName"].'</td>';
echo '<td>'.$row["phName"].'</td>';
echo '<td>'.$row["testHistoryDate"].'</td>';
echo '<td>'.$row["type"].'</td>';
$type = $row['type'];
$testHistoryDate = $row['testHistoryDate'];
?>
<td>
<span id='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer' value='<?php echo $row['testAnswer']; ?>' />
</span>
</td>
<td>
<input type='submit' value='Edit' name='edit' id='edit' onclick="sendToEdit('<?php echo $row['pID'] ?>','<?php echo $row['phID'] ?>', '<?php echo $row['testHistoryDate'] ?>', '<?php echo $row['type'] ?>')" />
</td>
</tr>
<?php } ?>
tl;dr
So it isn't completely clear what you are trying to do here but I can explain a couple things that might help.
in html ids should be unique. You dont have to obey this rule for your page to work but you have found one of the consequences if breaking it: jQuery will only find the first one.
it is a good idea to base html ids on some unique attribute of your data eg the table row id.
You can get more creative with your jQuery selectors for example
$('input[type="text"]') // gets all the text inputs
Use classes. When you want to be able to easily select all of a group of html elements you should give them all the same class name. one element can have multiple class names and many elements can share a class name. you can then select them by class name using jquery like this:
$('.myclassname')
I think you need to change your php to look more like this:
<span class='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer-<?php echo $row['id'] ?>' value='<?php echo $row['testAnswer']; ?>' />
</span>
Since you're creating elements inside a php loop, you must be sure that every element has a unique id (or no id at all). You can use either an incrementing index, or some unique value in your array. At first glance, seems that $row['pID'] is a good candidate:
<input id='edit_<?php $row['pID'] ?>' type='submit' value='Edit' ... />
After that you should be able to target individual elements.
I just finished my news posting system and I need help to make the news deletion system.
Right now I have this code to load the each post ID and TITLE into a table as well as a checkbox beside it.
<?php
$news = mysql_query('SELECT `id`,`title` FROM news');
if (!$news)
{
exit('<p>Error retrieving news from database!<br />'.
'Error: '.mysql_error().'</p>');
}
while ($new = mysql_fetch_array($news))
{
$id = $new['id'];
$title = $new['title'];
echo "<tr style='background: #3D3D3d; width: 400px; font-family: Century Gothic; font-size: 15px;'>";
echo "<td style='padding-left: 5px'><input type='checkbox' name='id' value='$id' /></td> <td style='padding-left: 15px'>$id</td> <td style='padding-left: 15px'>$title</td>";
echo "</tr>";
}
?>
I want to know how to delete each database record by id using checkboxes.
First i would recommend an Archive system over Deleting just so that the data is stored for any reason you would have to call on it, no matter how little importance the entry has.
an idea would be to break up the code so that it makes it easy to read:
All styles into a CSS file or CSS script takes and use classes and
IDs to set up style (its a bit hard to read your code)
Have SQL procedures call to manage the SQL data to make your code
able to change from PHP to something else if you ever need to
to add my idea to the code
<?php //deletenews.php
//....
$result = $mysql_query("Call Delete_news_Entry($id)");
if (!$result)
{
die("Error deleting record from news" . mysql_error);
}
//.... end of php
?>
SQL Procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS $$
CREATE PROCEDURE DB.Delete_news_entry(in_ID INTEGER)
BEGIN
DELETE FROM news WHERE id=in_ID;
END $$
DELIMITER ;
(if you want it to be live over submit button)
javascript
<Script type='text/javascript'>
//depends on jquery
function deletenews(id)
{
var spanid = "#span"+id;
$.get("deletenews.php",
null,
function(){
Alert("Complete") //this is more or less for you to put your required code here
$(spanid).hide();
},
"html")
.error(function(){
Alert("error") // for your own code to go here
});
}
</script>
sorry, just modifying your code
//in your php code, for the event, try onclick or onchange to trigger the delete
echo "<span id='span$id'><td class='left'><input type='checkbox' name='id' value='$id' onclick='deletenews($id)' /></td><td class='left'>$id</td> <td class='left'>$title</td></span>";
Having everything a part makes it easy to read.
i have been practicing breaking my code up for a long time now, i even draw maps of how all my files relate instead of having a page of php 1000 lines of code or more.
Right now it seems that you're only creating the table rows, but I'm gonna go ahead and assume these are within in the table element. If this table is also within a form element, you can delete all the records with a checked checkbox on submit.
You need to use the PHP isset function in the form's action reference to check if the checkbox is set and a foreach loop to run through them all. Something like this:
<?php
foreach($_POST as $key =>$value){
if(isset($_POST[$key])){
$value = mysql_real_escape_string($value);
mysql_query("DELETE FROM table WHERE id = $value");
}
}
?>