简体   繁体   中英

Inline CKEditor save to MySQL using AJAX/PHP

I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.

For some reason, nothing happens when I click the save button.. not even in the console.

It's just using jQuery at the moment, will I have to use AJAX for this?

If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.

Here is my code:

index.php

          <div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">    
           <?php
            $query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
            $show = mysql_query($query3, $con);
            while ($row = mysql_fetch_array($show))
            {
              echo $row['file'];
            }
            ?>
        </div>
        <button type="button" id="save"><span>Save</span></button>
            <script>
               $(document).ready(function (e) {

                  $("#save").click(function (e) {
                      var data = CKEDITOR.instances.caption1.getData();
                      var options = {  
                           url: "save.php",
                          type: "post",
                          data: { "editor" : encodeUriComponent(data) },
                         success: function (e) {
                           echo "Succesfully updated!";
                         }
                       };
                  }
               });
            </script>
      </div>

save.php

     <?php
$connection = mysql_connect("localhost", "", ""); 
$db = mysql_select_db("castle", $connection); 
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>

You need to send the data to the server like this;

$.ajax({
   url: "save.php",
   data: {
      "editor" : encodeUriComponent(data)
   },
   error: function() {
      //Error
   },
   success: function(data) {
      //Success
   },
   type: 'POST'
});

Currently you are just creating an object called 'options'

Your code should look like this;

$("#save").click(function (e) {
  var data = CKEDITOR.instances.caption1.getData();
  $.ajax({
   url: "save.php",
   data: {
       "editor" : encodeUriComponent(data)
   },
   error: function() {
      //Error
   },
   success: function(data) {
      alert('Success');
   },
   type: 'POST'
});

}

Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM