Save data to PHP / Mysql with inline edit in CKEditor - php

I want to use "inline edit" of the new CKEditor 4 (http://docs.ckeditor.com/#!/guide/dev_inline-section-2), but can not find any example of how to save the data with PHP / MySQL.
Can you help me?

You need some AJAX magic. Via JavaScript inside the page you get the edited HTML. Then you send it to the server where a PHP script gets it and can pass it onto MySQL.
Here is a simple test case which will show you the ropes.
Let's start with the editable HTML.
<div id='textToBeSaved' contenteditable='true'>
<p>Using the <strong>Terminal</strong> in OS X makes you all-powerful.</p>
</div>
We also need a "Save" button which will be used to start the POST event.
<button onclick='ClickToSave()'>Save</button>
Such a button could well we positioned in the CKEditor toolbar itself, but that would require more coding and I'll leave it to someone who's better at JavaScript than me.
Of course you want to include CKEditor. For my sample code I'll also make use of jQuery, which I'll use for AJAXing the results.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='CKEditor4/ckeditor.js'></script>
Now the script which will execute when you press the "Save" button. It will use CKeditor to grab the edited HTML, then jQuery to send it.
<script type='text/javascript' language='javascript'>
// <![CDATA[
function ClickToSave () {
var data = CKEDITOR.instances.textToBeSaved.getData();
$.post('save.php', {
content : data
})
}
// ]]>
This is it, you don't need anything else clientside.
On the server, you must have the PHP code which will act when the script POSTs the updated HTML. The script must be called save.php and be positioned in the same directory where the HTML is if you use my code verbatim.
My one-liner here will just save your HTML in a temporary file inside the /tmp folder. Feel free to add your MySQL magic instead.
<?php
file_put_contents('/tmp/serverside.html', $_POST['content']);
?>

This is the way I've done it in the past:
The current_page_id relates to the table row we wish to update, otherwise we wouldn't know what record we need to update.
<div id="editable">My body text</div>
<input type="hidden" name="page_id" id="current_page_id" value="10" />
<script type="text/javascript">
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline('editable', {
on: {
blur: function( event ) {
var params = {
page_id: $("#current_page_id").val(),
body_text: event.editor.getData()
};
$.ajax({
url: 'php_file_to_post_to.php',
global: false,
type: "POST",
dataType: "text json",
data: params,
success: function(result) {
console.log(result);
}
});
}
}
});
</script>
The inside of your php_file_to_post_to.php PHP file you simply catch the ajax post request and update the row based off of the page_id variable which has also been posted along with the edited content.

This is how you will get text area data
CKEDITOR.instances.editor1.getData()
CKEDITOR is nothing but the object you used to create functionality.

Thanks so much for the code. Try to improve de code with file_put_contents('page.php', stripslashes($_POST['content']));
And add to the div onBlur="ClickToSave()" and now you can to delete de save button.

Related

jQuery not updating div content after database update

I am loading a php file in a div using jQuery. The php file displays the content of a MySQL database. It works fine but here is the problem: if I make a change to the database, I add a row for example, the div does not reflect the change. Whatever I do I just see the data as they were the first time I accessed the page.
The code I am using is pretty simple:
// This goes into head
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('displaydata.php?id=' + id);
}
</script>
// Set id to '1' onload
<body onload="recp('1')">
// Then I have a few links that will change the value of id onclick
Materials | Manufacturing
// Finally my div
<div id='myStyle'>
</div>
I do not put here the displaydata.php code. Anyway it is just a simple php file that SELECT and ECHO data.
Does anyone know what I am doing wrong? Why the div does not reflect the changes I make to the MySQL database? Thanks.
I would suggest you to think of a problem in terms of caching. If you are okay with moving away from load method, you could take a look at following code and make it into a right use.
var recp = function(id) {
$.ajax({
url: '/displaydata.php?id=' + id,
cache: false,
dataType: 'html',
success: function(data) {
$('#myStyle').html(data);
}
});
};
Hope it helps.
Is your php page cached? If you're making changes to the database behind the scenes, you need to clear your cache.

Script Execution with .load()

I have a form inside a DIV (normally the div is hidden using "display:none;")
The user open the DIV with: onclick='$("#Details").show("slow");
Fills out the form and save the data.
I don't want the entire page to be reloaded, and I need only this DIV to be reloaded
I tried:
function(data) {
$('#Detalils').load(location.href + ' #Detalils');
});
and:
$("#Detalils").load(location.href + " #Detalils, script");
and:
$('#Detalils').load(location.href + ' #Detalils', function() {
$('#script').hide();
})
where in #script I put my script
In this div I have some script, and because of the jQuery on load script execution, the script is not executed.
I cannot put the script in an external file, it must be in the page body.
Is there a way to execute the script a well?
Thanks
Your actual Javascript code should not be within the div, that is the issue. If you wish to reload the form for the user to enter new data, then use ID's on the elements within your forms and write your JQuery code outside of it or in an external file, here is a simple example :
Instead of something like :
<form>
<input type="button" onclick="alert('hello');"> Click me ! </input>
</form>
Do something like :
<form>
<input id="myButton" type="button"> Click me ! </input>
</form>
<script type="text/javascript">
$("#myButton").click(function()
{
alert('hello');
});
</script>
You will have to adapt your code to this, of course, but you don't have another choice. HTML code can be removed and added at will, but Javascript code must not be treated the same way. There are many reasons for this, but one reason is that the browser will only load the Javascript functions once, for obvious optimization reasons.
The works within my local environment. Give it a shot in yours.
The HTML:
<div id="wrapper">
Remove
Reload
<div id="Details">my details box</div>
</div>
The jQuery:
<script type="text/javascript">
function mload() {
/*LOAD IN MY EXTERNAL STUFF*/
mtarget = $('#Details'); //the element on your page, that houses your external content
mscript = 'external.js'; //the js script required for your plugin to work
mtarget.load("external.html", function(){
$.getScript(mscript, function() {
//run the plug-in options code for your external script here
});
});
//*/
}
function madjustments() {
/*ADJUST THE LOADING PROCESS*/
//remove the load request on click from your remove button
$('#mremovebtn').on("click",function(e) {
e.preventDefault();
$('#Details').children().remove();
});
//reload the request on click from your reload button
$('#mreloadbtn').on("click", function(e) {
e.preventDefault();
mload();
});
//*/
}
(function($){
mload();
madjustments();
})(jQuery);
</script>
You will obviously need 2 additional files. One called external.html and another called external.js, for my demo code to work. But you can change the naming process to whatever works for you.
Extra:
Set a class in your external html file (on the parent element), for example #external. And by default, set the CSS to display:none in the style sheet. Then when the page loads in, simply show() it in the jQuery code.

Why does a submission form work, but my ajax doesn't?

I am trying to create a button on my chat that will allow someone to print the conversation. So I made the button that runs a PHP script that creates a new file, writes the conversation to file, and also writes the following jQuery.
jQuery AJAX Call
function OnBeforeUnLoad () {
$.ajax({
type: 'GET',
url: 'deleteFile.php',
data: {
pageName: ".$pageName."
},
dataType: 'text',
success: function(data){alert('Good bye 1!');}
});
return;
}
HTML Put into page
<br/><br/><form method="get" action="deleteFile.php"> <input type="submit" value="Close this Window"/>
<input type="text" value="'.$pageName.'" name="pageName" style="visibility:hidden"/></form>
deleteFile.php
<?php
$pageName = $_GET['pageName'];
$fullURL = 'PrintPage'.$pageName.'.php';
unlink($fullURL);
echo '<script>window.close();</script>';
?>
When the page shows up and I click the "Close this Window" button it does exactly what I want. It deletes the file and closes the window. But I do not get the same results when I close the window (aka OnBeforeUnLoad()). I even tried triggering submit by giving the form an id of deleteFiles and then doing $('#deleteFiles').submit() and it still didn't work.
How do I get the AJAX to work within the OnBeforeUnLoad function?
The form calls the data pageName but the ajax calls it url.
You probably don't want to prefix and suffix the value with . characters either.
Feel like a dummy.... After making all those changes... I found out all I needed to do was add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
to the header.
Because I was dynamically creating the page in php, I forgot I needed to readd the jQuery.
Always the small things.. Thanks everyone for the help.

Can a variable go to a hidden PHP page using jQuery?

My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>​
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});​
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>​
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,

HTML form with PHP

I'd like to have a form that executes some php code without having to open a completely new php page. Right now, I'm familiar with "POST" so that I can execute a php file and call the variables from the HTML form using $_POST[variable] but, it takes time to open a new page, and I want to have a form that does the action right then and there.
For example, can someone write html code that creates a text box and a button, and when the user presses go, it displays the text that the user entered right next to the button.
Thanks!
Here's an HTML and PHP snippet to get you started. It uses jQuery and just writes the value of textarea beneath the submit button using AJAX.
HTML Snippet [file=so.html]
<!DOCTYPE html>
<html><head><title>SO Example</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js">
</script>
</head>
<body>
<form id="frm" name="frm">
<textarea id="txt" name="txt" rows="4" cols="40">
</textarea><br />
<input type="submit"><br />
<span id="result"></span>
</form>
<script type="text/javascript">
$('#frm').submit(function(e){
e.preventDefault();
$.ajax({
url:"/so.php",type:"post",dataType:"html",
data:$('#frm').serialize(),
success:function(obj){
$('#result').text(obj);
}
});
});
</script>
</body>
</html>
PHP Snippet [file=so.php]
<?php
echo $_POST['txt'];
If you want to execute php code after the page is loaded without opening a new page then you should be using a technology like AJAX. PHP is a pre-processor and is meant to be run to process a page, not for functions after that.
With AJAX you can use javascript to call a webpage that's processed by PHP. Then with that returned page/data you can do your page function.
For more info on ajax check here: http://en.wikipedia.org/wiki/Ajax_(programming)
I recommend looking at jQuery as an ajax wrapper: http://api.jquery.com/jQuery.ajax/
You can find a ton of tutorials online to get you started.
I'd look into AJAX, more specifically an AJAX call using jQuery. It looks a little bit like this for a POST request:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
});
And if I filled that out, it might look like this:
$.ajax({
type: 'POST', // Method of submission: POST or GET
url: 'processor.php', // The script to send to.
data: { id: 1, name: 'John' }, // The data to give to PHP.
success: function(data) { // Do something with what PHP gives back.
console.log(data);
}
});
For more info on jQuery's AJAX functions, head here: http://api.jquery.com/category/ajax/
You're interested in jQuery.ajax(), jQuery.post(), and jQuery.get() probably.

Categories