Kamil Wojdyło
Kamil Wojdyło

Reputation: 21

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,

I created a textarea in PHP where:

<textarea name="body" id="body"><?php echo $body?></textarea>

and

<script type="text/javascript">
  $(document).ready( function() {
  $("#body").Editor();
  });
</script>

Now i need to get value of this area for send it to SQL

if (isset($_POST['add-article'])) {     
  unset($_POST['add-article']);
  $_POST['user_id'] = $_SESSION['id'];
  $_POST['username'] = htmlentities($_SESSION['username']);
  $_POST['published'] = isset($_POST['published']) ? 1 : 0;
       
// I need this line
  $_POST['body'] = htmlentities($_POST['body']);

When I put text into this editor, it doesn't enter (value) into the textarea. I have to have value before I press the add-article button, beacuse now it gives me an empty text.

I found something like this

function displayText(){
  alert($("#body").Editor("getText"));
}

This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.

Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.

I think about if there is an error for example "Title already exist" follows:

} else {
    
  $title = $_POST['title'];
  $body = $_POST['body'];
  $category_id = $_POST['category_id'];
  $published = isset($_POST['published']) ? 1 : 0;
}

In my honest opinion i need something like:

add-article.addEventListener('click', function {
  $body (from PHP) = alert($("#body").Editor("getText"))(from JS); 
}

Thank you in advance for help.

Upvotes: 2

Views: 125

Answers (1)

Kinglish
Kinglish

Reputation: 23654

On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.

Add a script to your form submit to put the texteditor content into this element

<form onsubmit='return getItReady()'>

Add an element to the form you'll use as a proxy element and keep it hidden, something like

 <textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>

Then add the script to prepare it

<script>
function getItReady() {
 console.log('The content:', $('#body').Editor("getText"));
 $('#txtEditorContent').val($('#body').Editor("getText"));
 return true;
}
</script>

Then in your PHP, it will come through as $_POST['txtEditorContent'].

Upvotes: 2

Related Questions