I've succeeded to write a simple commenting system with a form of 2 fields: name and comment. When the user inters values and presses submit it simply adds the comment to the current page using Ajax (without loading the whole page).
Now, I need also to add the ability of "Deleting Comment", but I have no idea how can I implement that.
If you take a look at my code bellow you would notice that when loading the page I printed all the existing comments, and when adding new ones I simply added them to the HTML code by this sub-code:
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
I thought of declaring an array that holds the values of all the comments with an additional value for each one "active".
When this value is trua I print the current comment, else I dont.
I've not succeeded to implement that, besides, Is it a good solution at all?
cause this solution prints all the comments all over again each time the user presses submit.
Any suggestions?
I would appreciate your help.
This is My Code:
main.php
<html>
<head>
<title> </title>
<script language="Javascript" src="ajax.js"> </script>
</head>
<body>
<h1 align="center"><font color="#000080">Welcome, </font></h1>
<p align="center"><font color="#000080">Enter your name & comment then press
"Submit Button"</font></p>
<form name="f1" method="post">
<p align="center"><font color="#000080">
Enter your name: <input type="text" name="username" id="username">
<font color="#000080">
Enter your comment: <input type="text" name="comment" id="comment">
<input value="Submit" type="button"
onclick='JavaScript:postRequest()' name="showdate"></font></p>
</form>
</br></br>
<?php
include_once("config.php");
$query = "SELECT * FROM `comments` ORDER BY 'id'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center">';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
?>
<div id="result" align="center"> </div>
</body>
</html>
showcomments.php
name: ' .$name;
echo 'comment: ' .$content;
echo ''
?>
ajax.js
function postRequest() {
var xmlHttp;
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var usr=window.document.f1.username.value;
var cmnt=window.document.f1.comment.value;
var url = "showcomments.php?username=" + usr +"&comment=" + cmnt;
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange =function(){
if(xmlHttp.readyState == 4){
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(url);
}
function updatepage(str){
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
}
(P.S: I created a table using MySql named "comments" with the following columns: Id, Added_by, comment.)
I would not only print the name and comment in you PHP file, but also a form with a hidden field containing the ID. Or, even better, a button with a onClick="deleteComment(ID)". More importantly: place every comment in a p-tag with an ID, with id=comment-id. Your main.php PHP file would be expanded with this:
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center" id="'.$row['id'].'>';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
This (ajax)-function deleteComment(ID) then sends the ID of the comment to be deleted to another PHP-script. This deletes it from the database.
Now you have two options: you either delete the p-tag on the page by it's ID (this is very easy with jQuery with the function $('IDofP').empty(); ) or you reload all the comments.
Related
Im trying to use PHP to delete a row in a SQL database.
The row is decided by the name of the product the user types in.
I created a simple form to delete products that have already been entered:
<article>
<section>
<fieldset><legend><span>Would you like to add a Product?</span> </legend>
<form method="POST" id = "myForm" name="myForm" onsubmit="return false;">
<br>
<p>Enter a name of product <input type='text' id='name' name = 'name'/></p>
<br>
<input name="submit" id ="submit" type="button" value="Find Product"/>
</form>
</fieldset>
<div id="fetchProduct">
</div>
</section>
</article>
Say I have already entered the data on another form and it goes into the database, but when I try to delete it I am getting the Undefined index: name in error when i try to delete.
Here is the script im using to delete the product:
<?php
include("database/connect_database.php");
$name = $_POST['name'];
$query = "DELETE FROM products WHERE product_name = '$name' ";
$result = $database->query($query) OR die ("Failed query $query");
echo $database->error."<p>";
if($result){
echo "Record deleted";
}
else {
echo "Product not found!";
}
?>
Im also using AJAX to pass through the name:
fetch = function () {
// declare the two variables that will be used
var xhr, target, changeListener;
// find the element that should be updated
target = document.getElementById("fetchProduct");
var name = document.getElementById("name").value;
var variable = "name="+name;
// create a request object
xhr = new XMLHttpRequest();
changeListener = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "deleteProductSQL.php", true);
xhr.onreadystatechange = changeListener;
xhr.send(variable);
};
pageLoaded = function () {
var fetchButton = document.getElementById("submit");
if (fetchButton) {
fetchButton.addEventListener("click", fetch);
}
};
window.onload = pageLoaded;
Could anyone point out where im going horribly wrong here because I just cant identify why it isn't allowing me to delete the row and why im receiving the undefined error.
Thankyou for your time
Put your PHP code in isset()
if (isset($_POST['name']){
//code here
}
Also
<p>Enter a name of product <input type='text' id='name' name = 'name'/></p>
In this line, <p> is not a self-closing tag so
<p>Enter a name of product <input type='text' id='name' name = 'name'></p>
I have a page on my website that is dynamically created with information from an SQL database. As well as the data being displayed a delete link is also created for each record which links to a php file called deleteRecord.php that deletes that record from the database.
Is there any way I can incorporate a confirmation message so that when the Delete link is clicked it will only run the deleteRecord.php file if the response is Yes?
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
Delete
In a function:
Delete
and then put this in <head>:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
Delete
And put this in <head>:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
You can do it with an confirm() message using Javascript.
Try this one :
<script type="text/javascript">
var baseUrl='http://example.com';
function ConfirmDelete()
{
if (confirm("Delete Account?"))
location.href=baseUrl+'/deleteRecord.php';
}
</script>
echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';
<?php
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));
if(isset($_POST[add]))
{
$sno = mysqli_real_escape_string($con,$_POST[sno]);
$name = mysqli_real_escape_string($con,$_POST[sname]);
$course = mysqli_real_escape_string($con,$_POST[course]);
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";
//echo $query;
$result = mysqli_query($con,$query);
printf ("New Record has id %d.\n", mysqli_insert_id($con));
mysqli_close($con);
}
?>
<html>
<head>
<title>mysql_insert_id Example</title>
</head>
<body>
<form action="" method="POST">
Enter S.NO: <input type="text" name="sno"/><br/>
Enter Student Name: <input type="text" name="sname"/><br/>
Enter Course: <input type="text" name="course"/><br/>
<input type="submit" name="add" value="Add Student"/>
</form>
</body>
</html>
Another method using both onlcick & form submit button with php record id value (record to be delete).
Use php code to get the record ID to be deleted. This is working for me.
<form action="deleteRecord.php" method="POST">
<button onclick="return confirm('Are you sure! want to delete?')" type="submit" name="id" value="<?=$record['id'];?>" >Delete</button>
</form>
deleteRecord.php example file
<?php
$con=mysqli_connect("localhost","root","","dbname") or die(mysqli_error($con));
if(isset($_POST['id']))
{
$id = mysqli_real_escape_string($conn, $_POST['id']);
$query = "DELETE FROM table_name WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
}
mysqli_close($con);
if($query_run)
{
echo "Deleted Successfully";
exit(0);
}
else
{
echo "Not Deleted";
exit(0);
}
?>
I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean
I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that's why i don't want to refresh my page.
thanks in advance.
<?php
if(isset($_POST["search"]))
{
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
$rowID=1;
while($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td width='130px' id='name.$rowID.'>$row[Name]</td>";
echo "<td width='230px' id='link.$rowID.'><a href = '$row[Link]'>$row[Link]</a></td>";
echo "<td width='130px' onclick='Display($rowID);'>$add_to_textbox</td>";
echo "</tr>";
$rowID++;
}
echo "</table>";
#**********************
mysql_free_result($rs);
}
?>
<script type="text/javascript">
function Display(rowID){
var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/<\/?[^>]+(>|$)/g, "\n");
document.getElementById("name").value = document.getElementById('name'+rowID+'').innerHTML;
document.getElementById("link").value = linkVal;
}
</script>
here is my code
Well, you need to use the javascript / ajax.
Example: on your submit link (a href for exaple), add call-in-to js function submitMe and pass on whatever variables you need
function submitMe() {
jQuery(function($) {
$.ajax( {
url : "some_php_page.php?action=getsession",
type : "GET",
success : function(data) {
alert ("works!"); //or use data string to show something else
}
});
});
}
IF you want to change some content dynamically, it is easy- you just need to create tags, and assign ID to them : <div id="Dynamic"> </div>
Then you load ANYTHING between those two tags using
document.getElementById("Dynamic").innerHTML = "<b>BOOM!</b>";
Meaning that you calling area between two tags and loading something into them. The same way you GET data from that place:
alert(document.getElementById("Dynamic").innerHTML);
Please read this:
http://www.tizag.com/javascriptT/javascript-getelementbyid.php
In addition, play and experiment with DOM elements and learn how they interact. It is not hard, just takes some time to grasp all concepts.
Whenever you send request ajax (with plain js anyway) from a html form, make sure you add the return false statement to prevent redirection:
something like:
<form method="post" ... onsubmit="ajax_post(); return false;">
You have to use ajax, but you can do it in plain javascript (without jquery). Jquery makes it easier.
plain javascript example: This function will trigger an ajax, via get, without parameter: you can tweak it so it run in POST and be able to send some parameter: file represent the php file to request and html represent the container whre the data will be displayed:
function plain_ajax(file,html){
if (window.XMLHttpRequest){
r=new XMLHttpRequest(); //For Most BRowser
} else{
r=new ActiveXObject("Microsoft.XMLHTTP"); //for Explorer
}
//When the state change
r.onreadystatechange=function(){
//ReadyState 4 = Loaded see: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
//status 200 = ok see: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if(r.readyState==4 && r.status==200){
//Replace the content with the response, Using creatDocumentFragment is more efficient
//at the cost of a few more lines But it would alos allow you to append the data
//instead of replacing it using innerHTML;
document.getElementById(html).innerHTML = r.responseText;
}
}
//Opening the connection and sending the request.
r.open("GET",file,true);
r.send();
}
Your HTML or PHP form
<form action="submit.php" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone Number: <input name="phone" id="phone" type="text" /><br />
<input type="button" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Your JavaScript
<script>
function SubmitForm() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.post("submit.php", { name: name, email: email, phone: phone },
function(data) {
alert("Data Loaded: " + data);
});
}
</script>
Your PHP page to do some activity
<?php
echo $_POST['name']."<br />";
echo $_POST['email']."<br />";
echo $_POST['phone']."<br />";
echo "All Data Submitted Sucessfully!"
?>
I have, with the help of the SO community written a javascript and php page that allows me to pass a value from the popup page back to the parent page.
This works 100% on internet explorer but not in google chrome or on my ipad / galaxt tablet.
Any idea on how this can be corrected? Any help appreciated as always.
Below is portions of my code from the parent page(newsale.php) and the popup page(sku.php). I know that other methods are recommended over using popup but I need to get this solution working with the popup page for application reasons.
newsale.php Parent Page (Code snippets, not entire page)
<script type="text/javascript">
function selectValue(id)
{
// open popup window and pass field id
window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
'width=1000,toolbar=1,resizable=1,scrollbars=yes,height=200,top=100,left=100');
}
function updateValue(id, value)
{
// this gets called from the popup window and updates the field with a new value
document.getElementById(id).value = value;
}
</script>
<table>
<tr id="r1">
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value)" <? if($rows>0){echo "value=".mysql_result($resultorder,0,1);} ?>><img src=q.png name="choice" onClick="selectValue('sku1')" value="?">
</td>
</tr>
<tr id="r2">
<td>
<input size=10 type=number id=sku2 name=sku2 onchange="showUser(2, this.value)" <? if($rows>1){echo "value=".mysql_result($resultorder,1,1);} ?> ><img src=q.png name="choice" onClick="selectValue('sku2')" value="?">
</td>
</tr>
</table>
sku.php Popup Page (entire page)
<?
$con = mysql_connect('localhost', 'username', 'password');
if (!$con)
{
die('Could not connect to server: ' . mysql_error());
}
$db=mysql_select_db("DBName", $con);
if (!$db)
{
die('Could not connect to DB: ' . mysql_error());
}
$sql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$result=mysql_query($sql);
?>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<script type="text/javascript">
function sendValue(value)
{
var e = document.getElementById("subcat");
value = e.options[e.selectedIndex].value;
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("subcat");
var catSelected = e.options[e.selectedIndex].value;
document.getElementById("copycat").value=catSelected;
}
</script>
<form name="testform">
Category: <select name=cat id=cat onchange="AjaxFunction(this.value);" style="width=300"> <br>
<option value='' style="width=300">Select One</option>
<br>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<br><br>
Pack Code:
<select name=subcat onchange="updateinput();" >
<br><br>
</select>
<br><br>
<input type=hidden name=copycat id=copycat >
<td><input type=button value="Select" onClick="sendValue(document.getElementById(copycat))" /></td>
</form>
dd.php (for dynamic drop down list)
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select concat(packcode,', ',description) as details from skudata where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[details]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>
I dont think dd.php has any influence on the functionality of the parent popup relationship but have included it so you can follow the code.
As mentioned this works 100% on Internet explorer but not in google chrome or my ipad.
When you use
document.getElementById("subcat");
then you should also have an element with such an id. Your
<select name=subcat onchange="updateinput();" >
won't do with browsers like chrome, firefox, konqueror and probably lots of others. Use
<select id="subcat" onchange="updateinput();" >
instead.
Unfortunately, I can't get your code to work so I can't test this, but changing
window.opener.updateValue(parentId, value);
to
window.opener.contentWindow.updateValue(parentId, value);
or
window.opener.window.updateValue(parentId, value);
may solve this.
If it doesn't, maybe you can post the errors that are showing from the Chrome console and explain better what exactly doesn't work.
In below function also,you called for subcat.
function sendValue(value)
{
var e = document.getElementById("subcat");
}
along with one mentioned by Themroc.
You should first have an id="subcat".
Still you getting some problem , post the error.
Thanks.