Luke Turnbull
Luke Turnbull

Reputation: 129

Emailing a Div's contents

I have a div in which it's contents are generated by JavaScript. I was wondering if it is possible to email the contents of the div? Also is it possible in JavaScript or must it be done in PHP?

Upvotes: 1

Views: 3330

Answers (3)

lukas.pukenis
lukas.pukenis

Reputation: 13597

This must be done in PHP, as JavaScript has no capability to send an email.

What can you do with JavaScript is - grab DIV contents and send the to PHP script which will send the email.

If you have something like this:

<form action="your_php_script.php" method="POST">
<textarea name="body"></textarea>
<input type="submit" value="Send" />
</form>

Then it will work without AJAX and will redirect you to your_php_script.php passing textarea value.

But if you want to send via AJAX, it can be simply done like this and plus some JS code:

$('form').submit(function() {
   var body = $('input[name="body"]').val();
      $.ajax({
         type: 'POST',
         data: 'body='+body,
         success: function() {
            alert('Message was sent');
         },
         error: function(error) {
            alert('Error occured: ',error);
         }
      });
   return false;
});

And inside your PHP script you grab the value with this:

$body = $_POST['body'];

Upvotes: 1

ColBeseder
ColBeseder

Reputation: 3669

You can't email directly from JavaScript in the browser. You need to send the information to a server side (eg. PHP) file.

You can do this using a form, but then you need a form field.

If it's a div, you should use JavaScript. You can send a request (using AJAX), or, if the information is short and non-sensitive, you can navigate to the PHP page that does the email sending and add the information to the URL string.

Here is a very quick mock-up of the code. In reality, you should filter inputs and write clean code and whatnot.

Javascript:

window.location.href= "http://www.myDomain.com/email.php?data=" + theData ;

where http://www.myDomain.com/email.php is the url of the php file and theData is a variable containing the content of the div.

PHP

<?php
  mail("[email protected]", "Content of div", $_GET['data']);  // arguments are: to, subject, body
?>

$_GET['data'] is the content sent by the JavaScript above.

I have not included the JavaScript to get the div content into the variable theData

Upvotes: 1

Vikdor
Vikdor

Reputation: 24134

Create a hidden form with a single textarea, set the form method to POST and action as "mailto:;subject:" and then submit it. The contents of the form, i.e. the contents of the DIV in the text area will be part of the body sent out as an email and the default email client on the machine will be opened to actually send the mail.

Upvotes: 1

Related Questions