-->

Pages

Tuesday 7 March 2017

Edit Content Page using Ajax, PHP, HTML and JS !

Nowadays it is quite common to see a web page that provides us the capability of editing the content that we are seeing on the page itself, for example when we type a comment of Facebook and we make some sort of mistake, we got the edit option there only and then we can rectify it, In this article of mine, I am providing a simple PHP + AJAX script along with the implementation of javascript functions to make a content editable on the go, and then save it into the database, in my case the database is MySql.

Source: Google Images


index.php file:

<html>
<head>
<title>Editable Content</title>
<script type="text/javascript">
//this below function is responsible for making the div editable
 function makeEditable(div){
    div.style.border = "1px solid #000";
    div.style.padding = "20px";
    div.contentEditable = true;
}
//this function will make the div read only and also will make an Ajax request to save the data
function makeReadOnly(div){
    div.style.border = "none";
    div.style.padding = "0px";
    div.contentEditable = false;
    
    if (div == "") 
    {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else
        {
            //Ajax code started
           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) {
                
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                //we are setting the response to the txtHint div
            }
        };

//here I am using the POST HTTP Method,addContent.php is my second file where insert code is written, and I have set async property to true
        
  xmlhttp.open("POST","addContent.php",true);

//as I am using POST method to send the data, we need to set Content-Type
        
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       
   //here I am setting the query String with the div Content and the Content ID

      var vars="q="+div.textContent+"-"+document.getElementById("ID").innerHTML;

        xmlhttp.send(vars); //sending the information
        document.getElementById("txtHint").innerHTML="Processing.....";//before getting the response this message will appear
    }
    
}


</script>

    <style>
    
    h2,div
        {
            text-align:center;
            margin-top:50px;
        }
    
    </style>
</head>
    <body>
       
    <h2>Content Editable Page </h2>
<!-- calling function when div is clicked and when the control id out of the div-->

<div onclick="makeEditable(this)" onblur="makeReadOnly(this)" id="mydiv">

<!--This below code is just to retrieve content from DB into the DIV-->  

<?php
  $servername="localhost";
  $user="root";
  $pass="root";
  $dbname="MyDB";
  $con=  mysql_connect($servername,$user,$pass);
  if(!$con)
  {
      echo "Not connected";
  }
  mysql_select_db($dbname);
  $query="select * from content_table order by ID desc LIMIT 1";
  $res=  mysql_query($query);
  while($result=  mysql_fetch_assoc($res))
  {
      $id=$result['ID'];
      echo $result['content'];
  }
  ?>
    
</div>
<p id="ID" style="display: none"><?=$id?></p><!--Containing the ID-->
<div id="txtHint"></div><!--Here our message will be shown-->
    </body>
</html>

addContent.php file:



<?php

error_reporting(0);//error_reporting is set to 0 to hide any unwanted warning

$q = $_POST['q'];//getting the value from the query String
$var=  explode("-", $q);//using explode function to split the values 
$servername="localhost";
  $user="root";
  $pass="root";
  $dbname="MyDB";
  $con=  mysql_connect($servername,$user,$pass);
  if(!$con)
  {
      echo "Not connected";
  }
  mysql_select_db($dbname);
$sql="Update content_table set content='$var[0]' where ID='$var[1]'";//running the update query to update the content rather than adding new all the time here var[0] will contain the text and var[1] will be containing the ID where we want to Update.
mysql_query($sql);
if(mysql_affected_rows()>0)
{
    ?>
<p style="color:green">* Successfully Added</p>// if success this response will be sent back
<?php
}
 else {
       ?>
<p style="color:red">* Not added</p>//if failed this reponse will be sent back
<?php
 }

?>

ScreenShots:
Make sure you have at least one record into the DB, otherwise, nothing will appear

Once you click on the content, it will become editable like this 

After editing the content just come outside the div and this will make an ajax request to the second page and if successful you will see a success message otherwise a failure message.

If you guys have any doubt in the above code, make sure to ask me! Make sure to create your own database and table to implement this code.


No comments:

Post a Comment

Thanks for Your Time!