Quiero enviar un fragmento de html al servidor usando XMLHttpRequest. El trozo que tengo es este:
<body id="publish"> <p>Vous avez à parler à vous même</p> <input type="button" name="Submit" value="Submit" onClick="SaveDomHTML()"> </body>JavaScript empaqueta este fragmento en 'contenido' y lo transfiere al servidor a través de un script PHP. El problema que encuentro es que cuando trato de imprimir el 'contenido' en un archivo del lado del servidor por php:
fwrite($fh, $content);Obtengo lo siguiente en lugar de mi fragmento html.
[object HTMLBodyElement]¡Además, php gettype ($ content) da una cadena y no un objeto!
He buscado una solución como:
How to get innerHTML of DOMNode? http://stackoverflow.com/questions/2087103/how-to-get-innerhtml-of-domnode Send POST data using XMLHttpRequest http://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequestPero ninguno de ellos trabaja para mí.
Cualquier ayuda para resolver el problema es muy apreciada.
Mis archivos completos, que fueron elaborados gracias a la Respuesta 1, pero en JavaScript en lugar de en jquery:
<!doctype html> <html lang="fr"> <head> <meta charset="iso-8859-1"> <title>Untitled Document</title> <script type="text/javascript" charset="iso-8859-1"> function SaveDomHTML(){ "use strict"; var content = document.getElementById('publish'); console.log("content:", content); var xhr = new XMLHttpRequest(); xhr.open("POST", "/cgi-bin/domsave.php", true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (this.readyState === 4 || this.status === 200){ console.log(this.responseText); } }; xhr.send("content=" + content); } </script> </head> <body id="publish"> <p>Vous avez à parler à vous même</p> <input type="button" name="Submit" value="Submit" onClick="SaveDomHTML()"> </body> </html>archivo PHP:
<?php $user_dom_html = 'user_dom_'.time().'.html'; $fh = fopen($user_dom_html, 'w'); echo $user_dom_html; $content = $_POST['content']; fwrite($fh, $content); fclose($fh); ?>Funcionalidad del lado del servidor Paso.
Punto hijo del tercer paso.
Necesita apuntar a su parte html DOM
Código js del lado del cliente.
$(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); var content = $('#html_dom').html(); $.ajax({ type: 'POST', url: 'dom_sever_file.php', data: {content: content} }).done( function( data ){ if(result){console.log("success")}; } ); }); });Código php del lado del servidor.
//get auth user. $user_session_id = $_SESSION['user_id']; $user_dom_html = "user_dom_".time()."html"; $fh = fopen($user_dom_html, 'w'); $stringData = $_POST['content']; fwrite($fh, $stringData); //need to store only html file name and user id in mysql //this part will be your mysql connection and insert query.