title: How to insert data into MySQL using PHP5 AJAX
body: <p>I am new in PHP5 and I want to insert data to my SQL using AJAX and jQuery. I have tried too many code to do that but not getting any positive response.</p>
  
  <p>Can any one help me to resolve my issue?</p>
  
  <p>PHP code:</p>
  
  <pre><code>&lt;?php
  class Crud{
  
  private $host="localhost";
  private $username="root";
  private $password="";
  private $db_name="comment-system";
  public $mysqli;
  
  public $data;
  
  public function __construct(){
  
      $this-&gt;mysqli = new mysqli($this-&gt;host, $this-&gt;username, $this-&gt;password, $this-&gt;db_name);
  
      if(mysqli_connect_errno()) {
  
          echo "Error: Could not connect to database.";
  
      exit;
  
      }
      /*else{
          echo"Your Database successfully connected"; 
      }*/
  
  }
  
  public function __destruct(){
      $this-&gt;mysqli-&gt;close(); 
  }
  
  public function read(){
  
      $query="SELECT * FROM test";
  
      $result= $this-&gt;mysqli-&gt;query($query);
  
      $num_result=$result-&gt;num_rows;
  
  
      if($num_result&gt;0){
          while($rows=$result-&gt;fetch_assoc()){
  
              $this-&gt;data[]=$rows;
  
              //print_r($rows);
  
          }
  
          return $this-&gt;data;
      }
  }
  
  public function insert($name){
  
   $query="INSERT INTO post SET post='$name'";
  
      $result= $this-&gt;mysqli-&gt;query($query) or   die(mysqli_connect_errno()."Data cannot inserted");
  
      if($result){
          header('location:index.php');   
      }
  }
  }
  
    //$obj=new Crud("localhost","root","","oop_crud");
  
   //$obj-&gt;read();
  ?&gt;
  </code></pre>
  
  <p>HTML code</p>
  
  <pre><code>&lt;script src="jquery-1.8.3.js"&gt;&lt;/script&gt;
  &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;&lt;/title&gt;
  &lt;meta name="" content=""&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="maindiv"&gt;
  &lt;h3&gt;post Detail:&lt;/h3&gt;
  &lt;h3&gt;&lt;textarea id="txtarea" &gt;my name is khan&lt;/textarea&gt;&lt;/h3&gt;
  &lt;h3&gt;&lt;button id="save" title="post"&gt;post&lt;/button&gt;&lt;/h3&gt;
  
  &lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>jQuery &amp;AJAX</p>
  
  <pre><code>&lt;script&gt;
  $("#save").click(function(){
      var name =$("#txtarea").val();
       $.ajax({
               type: "POST",
               contentType: "application/json; charset=utf-8",
                     url: "Crud/insert",
              data: "{'name':'" + name + "'}",
                async: false,
                success: function (responseText) {
                  alert(name);
             }
            });
   });
   &lt;/script&gt;
  
  &lt;/html&gt;
  </code></pre>