Delete and Edit a row in mysql with Ajax using php

I have a list of Article. And I want to use Ajax to Edit and Delete it.

Example: If i click edit button. It will show the form to edit the article. And when i submit the form it will updated without refresh page. And if i click delete button it will delete that aticle content in database and remove table row in the article list.

Thanks for ur help !
bathazarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

askanthonysCommented:
index.php {
<script type="text/javascript" language="javascript">

var rowShow=(document.all?'block':'table-row');

function editarticle() {

document.getElementById('edit').style.display = "none";
document.getElementById('doneediting').style.display = rowShow;
document.getElementById('deletearticle').style.display = rowShow;
document.getElementById('articletextbox').style.display = rowShow;
document.getElementById('articletextbox').value = document.getElementById('contentdiv').innerHTML;
document.getElementById('contentdiv').style.display="none";

}

function doneediting() {

document.getElementById('contentdiv').innerHTML = document.getElementById('articletextbox').value;
document.getElementById('contentdiv').style.display=rowShow;
document.getElementById('articletextbox').style.display="none";
document.getElementById('doneediting').style.display="none";
document.getElementById('deletearticle').style.display ="none";
document.getElementById('edit').style.display = rowShow;


var xmlhttp = false;
      if (window.XMLHttpRequest) {
                  xmlhttp = new XMLHttpRequest();
                  xmlhttp.overrideMimeType('text/xml');
      } else if (window.ActiveXObject) {
                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.open('GET', 'deletearticle.php?articleid=<? echo $_GET['articleid']; ?>&contents='+document.getElementById("articletextbox").value , true);
      xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            }
      };
      xmlhttp.send(null);

}




}

function deletearticle(articleid) {

x = confirm("Are you sure you want to delete this article?");

if(x) {
document.getElementById('edit').style.display="none";
document.getElementById('articletextbox').style.display="none";
document.getElementById('doneediting').style.display="none";
document.getElementById('deletearticle').style.display ="none";
document.getElementById('contentdiv').style.display=rowShow;
document.getElementById('contentdiv').innerHTML = "Article Deleted!";

var xmlhttp = false;
      if (window.XMLHttpRequest) {
                  xmlhttp = new XMLHttpRequest();
                  xmlhttp.overrideMimeType('text/xml');
      } else if (window.ActiveXObject) {
                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.open('GET', 'deletearticle.php?articleid='+articleid, true);
      xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            }
      };
      xmlhttp.send(null);

}



}


}


}

</script>


<?php

$articleid= mysql_real_escape_string($_GET['articleid']);


// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$result = mysql_query("SELECT * FROM '$tablename' WHERE '$idcolname' = '$articleid' ")
or die(mysql_error());

$row = mysql_fetch_array( $result );
// Print out the contents of the entry

echo "<div id=\"contentdiv\" name=\"contentdiv\">
echo $row[$datacolname];
echo "</div>"
echo "<textarea id=\"articletextbox\" name=\"articletextbox\" rows=\"50\" cols=\"200\"></textarea>";
echo "<br><input type=\"button\" id=\"edit\" name=\"edit\" onclick=\"editarticle();\">";
echo "<input type=\"button\" onclick=\"doneediting(\"".$_GET['articleid']."\");\" id=\"doneediting\" name=\"doneediting\" style=\"display:none\">";
echo "<input type=\"button\" onclick=\"deletearticle(\"".$_GET['articleid']."\");\" id=\"deletearticle\" name=\"deletearticle\" style=\"display:none\">";
?>











}

edit.php {

<?
$data = mysql_real_escape_string($_GET['contents']);
$articleid = $_GET['articleid'];



// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$result = mysql_query("UPDATE '$tablename' SET '$datacolname'='$data' WHERE '$idcolname'='$articleid'")
or die(mysql_error());

echo "<b> UPDATE SUCCESSFUL </b>";

?>







}

delete.php {


<?


$articleid = $_GET['articleid'];



// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

mysql_query("DELETE FROM '$tablename' WHERE '$idcolname'='$articleid'")
or die(mysql_error());


?>




}




now to explain it >_>


okay lets start with index.php

there is a script with the functions in it

the variable rowshow is what items are that are not display: none (invisible)

the first function is to edit the article

it makes the finish editing, delete, and text box visible
it hides the div with the article in it
it makes the contents of the text box those of the div

the second function is called when the user presses the "save" button

it hides the finish editing, delete, and text box
it shows the article div
it makes the contents of the div those of the text box
and then it queries with ajax to the other page

the third fuction is the delete function

it hides the finish editing, delete, and text box
it shows the article div
it queries with ajax to delete the table
it makes the contents of the article div "article deleted"


the php code puts the article contents into the div and echos all of the buttons and text boxes

the second file gets the contents and articleid of the article and then updates the row with the new contents


the third file gets the articleid and then deletes the row containing it


note in all files you need to set the variables  $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname

they are pretty self explanitory in their variable names

if you need more help with the code just ask

there may be a typo or two also

hope I helped

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bathazarAuthor Commented:
Your Solution is exellent. But your code is contain many error. Such as MySQL Syntax Error or in this code:

Please test your code and sent it againt. U helped so much. Thanks u and happy new year !
askanthonysCommented:
wow I had a lot of errors...

heres the fixed code:


index.php {


<script type="text/javascript" language="javascript">

var rowShow=(document.all?'block':'table-row');

function editarticle() {

document.getElementById('edit').style.display = "none";
document.getElementById('doneediting').style.display = rowShow;
document.getElementById('deletearticle').style.display = rowShow;
document.getElementById('articletextbox').style.display = rowShow;
document.getElementById('articletextbox').value = document.getElementById('contentdiv').innerHTML;
document.getElementById('contentdiv').style.display="none";
document.getElementById('contentdiv').innerHTML = "";

}

function doneediting() {



var xmlhttp = false;
     if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();
               xmlhttp.overrideMimeType('text/xml');
     } else if (window.ActiveXObject) {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.open('GET', 'editarticle.php?articleid=<? echo $_GET['articleid']; ?>&contents='+document.getElementById("articletextbox").value , true);
     xmlhttp.onreadystatechange = function() {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         
document.getElementById('contentdiv').innerHTML = document.getElementById('articletextbox').value;
document.getElementById('contentdiv').style.display=rowShow;
document.getElementById('articletextbox').style.display="none";
document.getElementById('doneediting').style.display="none";
document.getElementById('deletearticle').style.display ="none";
document.getElementById('edit').style.display = rowShow;
document.getElementById('articletextbox').value = "";
}
     };
     xmlhttp.send(null);

}






function deletearticle(articleid) {

x = confirm("Are you sure you want to delete this article?");

if(x) {
document.getElementById('edit').style.display="none";
document.getElementById('articletextbox').style.display="none";
document.getElementById('doneediting').style.display="none";
document.getElementById('deletearticle').style.display ="none";
document.getElementById('contentdiv').style.display=rowShow;
document.getElementById('contentdiv').innerHTML = "Article Deleted!";
document.getElementById('articletextbox').value="";

var xmlhttp = false;
     if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();
               xmlhttp.overrideMimeType('text/xml');
     } else if (window.ActiveXObject) {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.open('GET', 'deletearticle.php?articleid='+articleid, true);
     xmlhttp.onreadystatechange = function() {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          }
     };
     xmlhttp.send(null);

}



}







</script>


<?php


// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$articleid= mysql_real_escape_string($_GET['articleid']);

$result = mysql_query("SELECT * FROM ".$tablename." WHERE ".$idcolname." = '$articleid' ")
or die(mysql_error());

$row = mysql_fetch_array( $result );
// Print out the contents of the entry

echo "<div id=\"contentdiv\" name=\"contentdiv\">";
echo $row[$datacolname];
echo '</div>';
echo "<textarea id=\"articletextbox\" name=\"articletextbox\" rows=\"50\" cols=\"200\" style=\"display:none;\"></textarea>";
echo "<br><input type=\"button\" id=\"edit\" name=\"edit\" onclick=\"editarticle();\" value=\"Edit Article\">";
echo "<input type=\"button\" onclick=\"doneediting('".$_GET['articleid']."');\" id=\"doneediting\" value=\"Done Editing\" name=\"doneediting\" style=\"display:none;\">";
echo "<input type=\"button\" onclick=\"deletearticle('".$_GET['articleid']."');\" id=\"deletearticle\" value=\"Delete Article\" name=\"deletearticle\" style=\"display:none;\">";
?>
















}

deletearticle.php {




<?



// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$articleid = mysql_real_escape_string($_GET['articleid']);

mysql_query("DELETE FROM ".$tablename." WHERE ".$idcolname."='$articleid'")
or die(mysql_error());


?>






}


editarticle.php {



<?



// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$articleid = mysql_real_escape_string($_GET['articleid']);

$data = mysql_real_escape_string($_GET['contents']);

$result = mysql_query("UPDATE ".$tablename." SET ".$datacolname."='$data' WHERE ".$idcolname."='$articleid'")
or die(mysql_error());

echo "<b> UPDATE SUCCESSFUL </b>";

?>


}





I seem to have come upon a problem:

the article cannot contain these tags : </div> or </textarea>

if you need me to fix it I will try my best



also this should only be for administrators because it is probably vulnerable to sql injection
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

askanthonysCommented:
By administrators I mean that regular users should not have access to it
bathazarAuthor Commented:
- Can u have a Demo ? I still have many error

- If i open index.php file. I can't have any result because the script cannot find the query string variable is "articleid".

- If i del this (WHERE ".$idcolname." = '$articleid') i have a list of article and a button edit. When i click into the edit button it show the content of article and i can edit it. But i cannot update or delete it :(

- Can u fix it for me ?

- Thanks u very much. Nice help :)
askanthonysCommented:
I have a test running just fine for me on my server (tested in firefox and ie)

on index.php you must specify in the top like index.php?articleid=1

if you dont want to add the articles in manually you can just press edit and type something and save it






do you want to be able to edit all the articles on one page not specified by the query string?

like you just open up index.php and it lists like this:

article1:

This is article 1 this is some text that takes up some space.

[edit]

article2:

This is article 2 this is some text that takes up some space

[edit]

article3:

This is article 3 this is some text that takes up some space

[edit]

etc.

???


bathazarAuthor Commented:
- Yeah... I want to edit all article in the list page. So i need u help again...

- Thanks u very much. Nice help :)
askanthonysCommented:
ok Ill go get to work on that

prolly take me about 5-10 more minutes
askanthonysCommented:
all I changed was the index and the delete page so here they are:


index.php {


<script type="text/javascript" language="javascript">

var rowShow=(document.all?'block':'table-row');

function editarticle(editbutton, doneeditingbutton,deletearticlebutton,thearticletextbox,thecontentdiv) {

document.getElementById(editbutton).style.display = "none";
document.getElementById(doneeditingbutton).style.display = rowShow;
document.getElementById(deletearticlebutton).style.display = rowShow;
document.getElementById(thearticletextbox).style.display = rowShow;
document.getElementById(thearticletextbox).value = document.getElementById(thecontentdiv).innerHTML;
document.getElementById(thecontentdiv).style.display="none";
document.getElementById(thecontentdiv).innerHTML = "";
}

function doneediting(editbutton, doneeditingbutton,deletearticlebutton,thearticletextbox,thecontentdiv, thearticleid) {

var xmlhttp = false;
     if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();
               xmlhttp.overrideMimeType('text/xml');
     } else if (window.ActiveXObject) {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.open('GET', 'editarticle.php?articleid='+thearticleid+'&contents='+document.getElementById(thearticletextbox).value , true);
     xmlhttp.onreadystatechange = function() {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         
document.getElementById(thecontentdiv).innerHTML = document.getElementById(thearticletextbox).value;
document.getElementById(thecontentdiv).style.display=rowShow;
document.getElementById(thearticletextbox).style.display="none";
document.getElementById(doneeditingbutton).style.display="none";
document.getElementById(deletearticlebutton).style.display ="none";
document.getElementById(editbutton).style.display = rowShow;
document.getElementById(thearticletextbox).value = "";
}
     };
     xmlhttp.send(null);
}

function deletearticle(editbutton, doneeditingbutton,deletearticlebutton,thearticletextbox,thecontentdiv,articleid) {

x = confirm("Are you sure you want to delete this article?");

if(x) {
document.getElementById(editbutton).style.display="none";
document.getElementById(thearticletextbox).style.display="none";
document.getElementById(doneeditingbutton).style.display="none";
document.getElementById(deletearticlebutton).style.display ="none";
document.getElementById(thecontentdiv).style.display=rowShow;
document.getElementById(thecontentdiv).innerHTML = "Article Deleted!";
document.getElementById(thearticletextbox).value="";

var xmlhttp = false;
     if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();
               xmlhttp.overrideMimeType('text/xml');
     } else if (window.ActiveXObject) {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.open('GET', 'deletearticle.php?articleid='+articleid, true);
     xmlhttp.onreadystatechange = function() {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          }
     };
     xmlhttp.send(null);
}
}
</script>

<?php

$username = "jacware_ipnow";
$password = "asdfipnow";
$db = "jacware_ipnow";
$tablename = "articles";
$datacolname = "data";
$idcolname = "articleid";

// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$result = mysql_query("SELECT * FROM ".$tablename."")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
// Print out the contents of the entry
echo "<div id=\"contentdiv".$row[$idcolname]."\" name=\"contentdiv".$row[$idcolname]."\">";
echo $row[$datacolname];
echo '</div>';
echo "<textarea id=\"articletextbox".$row[$idcolname]."\" name=\"articletextbox".$row[$idcolname]."\" rows=\"50\" cols=\"200\" style=\"display:none;\"></textarea>";
echo "<br><input type=\"button\" id=\"edit".$row[$idcolname]."\" name=\"edit".$row[$idcolname]."\" onclick=\"editarticle('edit".$row[$idcolname]."','doneediting".$row[$idcolname]."','deletearticle".$row[$idcolname]."','articletextbox".$row[$idcolname]."','contentdiv".$row[$idcolname]."');\" value=\"Edit Article\">";
echo "<input type=\"button\" onclick=\"doneediting('edit".$row[$idcolname]."','doneediting".$row[$idcolname]."','deletearticle".$row[$idcolname]."','articletextbox".$row[$idcolname]."','contentdiv".$row[$idcolname]."','".$row[$idcolname]."');\" id=\"doneediting".$row[$idcolname]."\" value=\"Done Editing\" name=\"doneediting".$row[$idcolname]."\" style=\"display:none;\">";
echo "<input type=\"button\" onclick=\"deletearticle('edit".$row[$idcolname]."','doneediting".$row[$idcolname]."','deletearticle".$row[$idcolname]."','articletextbox".$row[$idcolname]."','contentdiv".$row[$idcolname]."','".$row[$idcolname]."');\" id=\"deletearticle".$row[$idcolname]."\" value=\"Delete Article\" name=\"deletearticle".$row[$idcolname]."\" style=\"display:none;\">";

}
?>


}


deletearticle.php {



<?


// $username AND $password AND $db AND $tablename AND $datacolname AND $idcolname NEED TO BE SET
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$articleid = mysql_real_escape_string($_GET['articleid']);

mysql_query("DELETE FROM ".$tablename." WHERE ".$idcolname."='$articleid'")
or die(mysql_error());

echo "<b>article deleted</b>";

?>


}


should work now
bathazarAuthor Commented:
Yeah !!! I can delete it. But i still can't Update it !!
bathazarAuthor Commented:
Perhaps it can received Article ID but it can't receive Article Conten :)
askanthonysCommented:
It worked for me.


I am not sure what the problem could be.

if you have firefox will you check if the javascript console says?



what exactly is it doing?

where does it get "stuck"?
bathazarAuthor Commented:
- It worked for me. I changed editarticle.php file so it does not work :)

- Thanks for your help.

- That code help me a lot for my work.

- Did you think about use <div><textarea> in that code. I think if u finish it, it will be a excellent code :)

- Anyway. Thank ur help.
askanthonysCommented:
Your ever so welcome

What about the <div> <textarea>?

I thought of that sorta idea if thats what you mean
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.