5

I have this Code:

<div contenteditable="true"><p><?php echo $row[1]; ?></p></div>

Can I take the contents of the div and send them as a POST parameter in order to use them in the PHP. It would be good if I can use: onchange="this.form.submit()".

Thanks!

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
nikitz
  • 1,051
  • 2
  • 12
  • 35
  • you echoed the contents, so you already have it in a variable. so what exactly do you want to do with `$row[1]` ? –  Feb 10 '14 at 22:52
  • The contents can be changed by the user. I use it like but in this way I don't have fixed width. – nikitz Feb 10 '14 at 22:57
  • @user3294900 - Have you ever looked into using [`stream_context_create`](http://php.net/manual/en/function.stream-context-create.php)? – admdrew Feb 10 '14 at 22:58
  • why not put it in an textarea, when they hit 'submit' its posted –  Feb 10 '14 at 23:27

1 Answers1

8

It is not possible to post contents of div tags, as this is only possible on form elements. The workaround for this would be to use some Javascript that populates a hidden field when a form is submitted, and the hidden field is posted instead.

Observe the following HTML. See that there is an onsubmit event attached to the form element. What we're saying to the browser here is when the form is submitted, first call the Javascript function process, and only submit if said function returns true:

<form method="post" action="process.php" onsubmit="javascript: return process();">
  <input type="hidden" id="hidden" name="content" vlaue="<?php echo $row[1] ?>">
  <div contenteditable="true" id="content"><p><?php echo $row[1] ?></p></div>
  <button type="submit">Post</button>
</form>

This would be your Javascript. What you're doing is getting the innerHTML of the element with the id content and assigning it to the value of the element with the id hidden and return true so the form can be successfully submitted:

<script>
function process() {
  document.getElementById("hidden").value = document.getElementById("content").innerHTML;
  return true;
}
</script>

And in the process.php file, just output the posted content:

var_dump("Posted content: " . $_POST['content']);

Hope this helps!

ninty9notout
  • 1,121
  • 8
  • 11