Jump to content

Recommended Posts

Hi there,

 

Say I have this code:

 

<div id="name>Lorem ipsum dolor sit amet.</div>

 

I want to take the text inside the div and put it into a table in a database, in the same manner you would post content from a form to a database. Is that possible?

 

And the follow-up question to that: How is it possible?

No, I want the opposite - I want to take the data from my div tags and put it in a database.

 

If you just want to display the data from your database into your div tags then

 

$result = mysql_query(" SELECT * FROM example ")
or die(mysql_error());  

$row = mysql_fetch_array($result);

echo "<div id='name'>".$row['text']."</div>";

You need to explain what it is your wanting to do in more detail by the sound of it. I moved the thread here because it sounded like you wanted to parse some data from a remote site.

 

If you just want to grap some content from one of your own pages and send it to a php script which will place it within a database you could easily achieve that with a litle ajax. I use jQuery as ena example....

 

var content = $('#name').html();
$.ajax({
  url: 'processingscript.php,
  type: 'POST',
  data: {
    content: content
  }
});

All right, I'll try to explain it in more detail:

 

I am going to use localStorage along with HTML5's new contentEditable feature to create a website that is editable directly from the browser. The localStorage should save what is written in a div with contentEditable=true on the client's computer. This is working:

<!DOCTYPE html>
<html>
<head>
<title>LocalStorage</title>
<script>
	var addEvent = (function () {
		if (document.addEventListener) {
			return function (el, type, fn) {
				if (el && el.nodeName || el === window) {
					el.addEventListener(type, fn, false);
				} else if (el && el.length) {
					for (var i = 0; i < el.length; i++) {
						addEvent(el[i], type, fn);
					}
				}
			};
		} else {
			return function (el, type, fn) {
				if (el && el.nodeName || el === window) {
					el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
				} else if (el && el.length) {
					for (var i = 0; i < el.length; i++) {
						addEvent(el[i], type, fn);
					}
				}
			};
		}
	})();

</script>
</head>
<body>
<div id="editable" contentEditable="true">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

<script>
	var editable = document.getElementById('editable');

	addEvent(editable, 'blur', function () {
	  // lame that we're hooking the blur event
	  localStorage.setItem('contenteditable', this.innerHTML);
	  document.designMode = 'off';
	});

	addEvent(editable, 'focus', function () {
	  document.designMode = 'on';
	});

	addEvent(document.getElementById('clear'), 'click', function () {
	  localStorage.clear();
	  window.location = window.location; // refresh
	});

	if (localStorage.getItem('contenteditable')) {
	  editable.innerHTML = localStorage.getItem('contenteditable');
	}
</script>

</body>
</html>

 

However, I'd like that when the client hits a 'Save' button or something, all the stuff from the localStorage gets sent to a table in a MySQL database.

 

How would you do that?

However, I'd like that when the client hits a 'Save' button or something, all the stuff from the localStorage gets sent to a table in a MySQL database.

 

How would you do that?

 

See my example above. It uses the jQuery library to grab the data from the div and send it to a php script which would then add it to the database.

I'm back ;)

 

All right, so how do I send the content? Do I create an input button inside a form element (I guess I'm not, as the jQuery script already tells the URL of the PHP file and that it should POST)?

 

Can I use a regular link to send it off?

 

And should the PHP file contain anything else that the database connection stuff and the code for putting the content in the tables?

Can I use a regular link to send it off?

 

You could execute that piece of code at the trigger of any event you like.

 

And should the PHP file contain anything else that the database connection stuff and the code for putting the content in the tables?

 

The php script acts just the same as it would if you where posting data to it via a form.

So, this is what I got (not working):

 

The saveToDb.php file:

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$sql="INSERT INTO Content (main)
VALUES
('$_POST[content]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>

 

The script that you provided me with:

	<script>
var content = $('#editable').html();
$.ajax({
	url: 'saveToDb.php',
	type: 'POST',
	data: {
		content: content
	}
});
</script>

 

The div and the button:

<div id="editable" contentEditable="true">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

<input type="button" value="Save" name="save" onclick="$.ajax">

 

When I click the button, it sends 'null' to the table. What am I doing wrong?

<script>
$(document).ready(function() {
    $('#save_editable').click(function() {
        var content = $('#editable').html();
        $.ajax({
            url: 'saveToDb.php',
            type: 'POST',
            data: {
                content: content
            }
        });
    });
});
</script>

<div id="editable" contentEditable="true">Lorem ipsum dolor ....</div>
<a id="save_editable">Save</a>

<script>
$(document).ready(function() {
    $('#save_editable').click(function() {
        var content = $('#editable').html();
        $.ajax({
            url: 'saveToDb.php',
            type: 'POST',
            data: {
                content: content
            }
        });
    });
});
</script>

<div id="editable" contentEditable="true">Lorem ipsum dolor ....</div>
<a id="save_editable">Save</a>

 

This works perfectly! Thank you so much!

  • 3 years later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.