views:

67

answers:

3

I have a string, get by Javascript (the content of a div!);
I want to write this string to PHP, because i want a text file with this content!

How is the best way to do this?




Edit[1]: Method Post doesn't works, because i have '<' chars and it erase them (i don't know why)... Example: I have #include <stdio.h> and when i call echo $_REQUEST just show #include ...

A: 

POST the string to the server, the simplest way is to add the value to a form on the page and submit it, but you could submit the value via AJAX if you like... here is the simple example.

<div id="mydiv">Hello World</div>

<form method="post" action="myphppage.php" id="myform">
    <textarea name="mytext" id="mytext"></textarea><br>
    <input type="submit" value="Create File">
</form>

<script type="text/javascript">
    document.getElementById("mytext").value = document.getElementById("mydiv").innerHTML();
    document.getElementById("myform").submit();
</script>
Sohnee
A: 

You could pass the string text via url to the .php file that will process it.

There are many ways to accomplish that, one, very simple, could be:

var text = "some";
var url = "http://myserver/webapp/file.php?content=" + text;
location.href = url;

or with form or with Ajax and so on...

xdevel2000
Don't forget to URL escape the data.
icktoofay
+1  A: 

For the Javascript part, I suggest using jQuery.ajax. It could be triggered, for example, when a button is clicked.

$.ajax({ 
  type: "POST",
  url: "process_ajax_div.php",
  data: { divHTML: $('#yourdiv').html() }, 
  success: function(){ alert('done!'); },
  error: function(){ alert('error!'); }
});

For the PHP part (file process_ajax_div.php) you can do something like this:

<?php
   $divHTML = $_POST['divHTML'];

   // now do whatever you want with $divHTML
?>
egarcia